A simple Django view that handles both GET and POST requests

gene_x 0 like s 338 view s

Tags: python

Below is a simple Django view that handles both GET and POST requests. This view will render a basic HTML form on a GET request and process the form submission on a POST request:

  1. First, let's create a Django model called Message in models.py:

    from django.db import models
    
    class Message(models.Model):
        content = models.TextField()
    
  2. Now, we'll handle the view logic. Create or update a views.py file:

    from django.shortcuts import render, redirect
    from .models import Message
    
    def message_view(request):
        if request.method == "POST":
            content = request.POST.get('content')
            Message.objects.create(content=content)
            return redirect('message_view')
    
        return render(request, 'message_form.html')
    
  3. Next, let's create a template message_form.html inside your app's templates directory:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Message Form</title>
    </head>
    <body>
        <form method="post">
            {% csrf_token %}
            <textarea name="content" placeholder="Enter your message"></textarea><br>
            <button type="submit">Submit</button>
        </form>
    </body>
    </html>
    
  4. Update your urls.py to include the view:

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('message/', views.message_view, name='message_view'),
    ]
    
  5. Ensure you have added your app and the django.middleware.csrf.CsrfViewMiddleware middleware in the INSTALLED_APPS and MIDDLEWARE settings respectively in your settings.py; Run migrations to create the Message model in your database:

    python3 manage.py makemigrations
    python3 manage.py migrate
    
  6. Start the development server:

    python3 manage.py runserver 0.0.0.0:80
    
  7. Now, if you navigate to http://127.0.0.1:8000/message/, you should see a simple form. Upon submission, the form content will be saved to the database.

[Without Model]

  1. Create or update a views.py file:

    from django.shortcuts import render
    from django.http import HttpResponse
    
    def message_view(request):
        if request.method == "POST":
            message = request.POST.get('content')
    
            # Convert the message to uppercase
            processed_message = message.upper()
    
            return HttpResponse(f"Received message: {processed_message}")
    
        return render(request, 'message_form.html')
    
  2. Let's reuse the template message_form.html from the previous example inside your app's templates directory:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Message Form</title>
    </head>
    <body>
        <form method="post">
            {% csrf_token %}
            <textarea name="content" placeholder="Enter your message"></textarea><br>
            <button type="submit">Submit</button>
        </form>
    </body>
    </html>
    
  3. Update your urls.py to include the view:

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('message/', views.message_view, name='message_view'),
    ]
    
  4. Ensure you have added the django.middleware.csrf.CsrfViewMiddleware middleware in the MIDDLEWARE setting of your settings.py; Start the development server:

    python manage.py runserver
    
  5. Now, when you navigate to http://127.0.0.1:8000/message/ and submit the form, you will receive a response showing the message you submitted without saving it to a database.

like unlike

点赞本文的读者

还没有人对此文章表态


本文有评论

没有评论

看文章,发评论,不要沉默


© 2023 XGenes.com Impressum