A simple Django view that handles both GET and POST requests 2

gene_x 0 like s 446 view s

Tags: python

Using Model

  1. Define your model:

    #In course/models.py:
    from django.db import models
    
    class Message(models.Model):
        content = models.TextField()
        created_at = models.DateTimeField(auto_now_add=True)  # Optional: to record when the message was created
    
    #python3 manage.py makemigrations
    #python3 manage.py migrate
    
  2. Convert your form to a ModelForm:

    #In course/forms.py:
    from django import forms
    from .models import Message
    
    class MessageModelForm(forms.ModelForm):
        class Meta:
            model = Message
            fields = ['content']
            widgets = {
                'content': forms.Textarea(attrs={'placeholder': 'Enter your message'})
            }
    
  3. Update your view to use the ModelForm and save messages:

    #In course/views.py:
    from django.shortcuts import render, redirect
    from .forms import MessageModelForm
    
    def message_view(request):
        if request.method == 'POST':
            form = MessageModelForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('course:message_view')  # Redirect back to the same view or another as per your choice
        else:
            form = MessageModelForm()
    
        return render(request, 'course/message_form.html', {'form': form})
    
    #course/views.py for retrieving and displaying the messages that have been saved in the database
    from django.shortcuts import render, redirect
    from .forms import MessageModelForm
    from .models import Message  # Import the Message model
    
    def message_view(request):
        if request.method == 'POST':
            form = MessageModelForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('course:message_view')  # Redirect back to the same view
        else:
            form = MessageModelForm()
    
        # Retrieve all saved messages
        messages = Message.objects.all()
    
        return render(request, 'course/message_form.html', {'form': form, 'messages': messages})
    
    # course/views.py for saving and displaying the uppercase of the input
    from django.shortcuts import render, redirect
    from .forms import MessageModelForm
    from .models import Message
    
    def message_view(request):
        if request.method == 'POST':
            form = MessageModelForm(request.POST)
            if form.is_valid():
                content = form.cleaned_data['content'].upper()  # Get and uppercase the input
                Message.objects.create(content=content)  # Save the uppercase content
                return redirect('course:message_view')
        else:
            form = MessageModelForm()
    
        messages = Message.objects.all()
    
        return render(request, 'course/message_form.html', {'form': form, 'messages': messages})
    
  4. The HTML remains almost the same:

    #In templates/course/message_form.html:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Message Form</title>
    </head>
    <body>
        <form method="post" action="{% url 'course:message_view' %}">
            {% csrf_token %}
    
            <!-- Display errors -->
            {{ form.content.errors }}
    
            <!-- Display textarea -->
            {{ form.content }}
    
            <br>
            <button type="submit">Send Message</button>
        </form>
    </body>
    </html>
    
    <!-- templates/course/message_form.html for retrieving and displaying the messages that have been saved in the database -->
    <!DOCTYPE html>
    <html>
    <head>
        <title>Message Form</title>
    </head>
    <body>
        <form method="post" action="{% url 'course:message_view' %}">
            {% csrf_token %}
    
            {{ form.content.errors }}
            {{ form.content }}
    
            <br>
            <button type="submit">Send Message</button>
        </form>
    
        <!-- Display saved messages -->
        <h2>Saved Messages:</h2>
        <ul>
            {% for message in messages %}
                <li>{{ message.content }} - {{ message.created_at }}</li>
            {% endfor %}
        </ul>
    </body>
    </html>
    
    <!-- templates/course/message_form.html with predefined templates -->
    {% extends "base.html" %}
    
    {% block title %}Message Form{% endblock %}
    
    {% block content %}
    <div class="container">
      <h1 class="text-center">Message Form</h1>
      <form method="post" action="{% url 'course:message_view' %}">
        {% csrf_token %}
    
        {{ form.content.errors }}
        {{ form.content }}
    
        <br>
        <button type="submit" class="btn btn-primary">Send Message</button>
      </form>
    
      <h2 class="text-center">Saved Messages:</h2>
      <ul class="list-group">
        {% for message in messages %}
          <li class="list-group-item">{{ message.content }} - {{ message.created_at }}</li>
        {% endfor %}
      </ul>
    </div>
    {% endblock %}
    
  5. Ensure your URLs are still set up properly:

    #In course/urls.py:
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('message/', views.message_view, name='message_view'),
        # ... your other urls
    ]
    

With these changes:

  • Messages submitted through the form will be saved in the Message model in the database.
  • After a successful form submission, the user will be redirected back to the message form view. Adjust this redirection as needed.
  • The form still uses a textarea for message content input.

Not Using Model

    # in course/forms.py
    from django import forms

    class MessageForm(forms.Form):
        content = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Enter your message'}))

    # in course/views.py
    from django.shortcuts import render, redirect
    from .forms import MessageForm

    def message_view(request):
        if request.method == 'POST':
            form = MessageForm(request.POST)
            if form.is_valid():
                # Here you can process the data.
                # For now, I'm just redirecting as an example.
                return redirect('some-other-view-or-url-name')
        else:
            form = MessageForm()

        return render(request, 'course/message_form.html', {'form': form})

    <!-- in templates/course/message_form.html -->
    <!DOCTYPE html>
    <html>
    <head>
        <title>Message Form</title>
        <!-- Optional: Add a link to a CSS stylesheet for styling. -->
    </head>
    <body>
        <form method="post" action="{% url 'course:message_view' %}">
            {% csrf_token %}

            <!-- Display errors -->
            {{ form.content.errors }}

            <!-- Display textarea -->
            {{ form.content }}

            <br>
            <button type="submit">Send Message</button>
        </form>
    </body>
    </html>

    # in course/urls.py
    from django.urls import path
    from . import views

    urlpatterns = [
        path('message/', views.message_view, name='message_view'),
        # ... your other urls
    ]

like unlike

点赞本文的读者

还没有人对此文章表态


本文有评论

没有评论

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


© 2023 XGenes.com Impressum