Django form processing: a full process guide from front-end to back-end

As an advanced Python web framework, Django has powerful form processing capabilities and can effectively handle user input, perform data validation and error handling. This article will introduce in detail how to create, process and use forms in Django.

1. The core of Django form system

Django’s form system handles the life cycle of the form, involving the following core parts:

  • Form class: Defines the structure and behavior of the form.
  • Validation logic: Ensures submitted data meets certain conditions.
  • Template: Displays the HTML representation of the form.
  • View: Handles the form submission process, including data validation and processing.

2. Create form class

Django’s forms module provides a flexible form class. You can define your own form class to represent an HTML form.

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

3. Process the form in the view

In Django views, you need to handle GET and POST requests. GET requests are typically used to display empty forms, while POST requests handle form submission data.

from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process form data
            return redirect('success_url')
    else:
        form = ContactForm()

    return render(request, 'contact.html', {'form': form})

4. Form validation

Django provides a powerful form validation system. When calling the is_valid() method, Django will clean the data and run all validators.

if form.is_valid():
    #The cleaned_data here is the verified data
    name = form.cleaned_data['name']
    email = form.cleaned_data['email']
    message = form.cleaned_data['message']
    # This data can be used to send emails or stored in a database

5. Use of forms in templates

In Django templates, forms are rendered into HTML. Django’s form class provides a variety of methods for rendering forms to HTML.

<!-- contact.html -->
<form method="post">
    {% csrf_token %}
    {<!-- -->{ form.as_p }}
    <input type="submit" value="Submit">
</form>

Use {{ form.as_p }} to render a form field as having

tags.

6. Error handling

If form validation fails, Django automatically adds error information to the form’s errors attribute.

<!-- Display field errors in template -->
{% if form.errors %}
    <ul>
        {% for field in form %}
            {% if field.errors %}
                <li>{<!-- -->{ field.errors }}</li>
            {% endif %}
        {% endfor %}
    </ul>
{% endif %}

7. Customized form style

You can customize the HTML of a form field by overriding the form’s default widget.

class ContactForm(forms.Form):
    #...
    message = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'special'})
    )

Within the template, you can further customize how the form is rendered.

<form method="post">
    {% csrf_token %}
    <div class="form-group">
        {<!-- -->{ form.name.label_tag }} {<!-- -->{ form.name }}
    </div>
    <!-- More fields -->
    <input type="submit" value="Submit">
</form>

8. Using ModelForm

When your form is related to a Django model, you can use ModelForm to simplify the process.

from django.forms import ModelForm
from .models import Contact

class ContactForm(ModelForm):
    class Meta:
        model=Contact
        fields = ['name', 'email', 'message']

9. Conclusion

Django’s form processing provides developers with powerful tools that not only make it easy to create forms, but also ensure the security and validity of data. Combining Django templates and views, developers can quickly collect, verify and process data.

By reading this article, you should have a detailed understanding of how Django handles forms. This is just a getting started guide, the real power of Django forms lies in their flexibility and extensibility. For more information, it is recommended to consult Django’s official documentation.


———————————END——————- ——–

Digression

Interested friends will receive a complete set of Python learning materials, including interview questions, resume information, etc. See below for details.

CSDN gift package:The most complete “Python learning materials” on the entire network are given away for free! (Safe link, click with confidence)

1. Python learning routes in all directions

The technical points in all directions of Python have been compiled to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the following knowledge points to ensure that you learn more comprehensively.

img
img

2. Python essential development tools

The tools have been organized for you, and you can get started directly after installation! img

3. Latest Python study notes

When I learn a certain basic and have my own understanding ability, I will read some books or handwritten notes compiled by my seniors. These notes record their understanding of some technical points in detail. These understandings are relatively unique and can be learned. to a different way of thinking.

img

4. Python video collection

Watch a comprehensive zero-based learning video. Watching videos is the fastest and most effective way to learn. It is easy to get started by following the teacher’s ideas in the video, from basic to in-depth.

img

5. Practical cases

What you learn on paper is ultimately shallow. You must learn to type along with the video and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

img

6. Interview Guide

CSDN gift package:The most complete “Python learning materials” on the entire network are given away for free! (Safe link, click with confidence)

If there is any infringement, please contact us for deletion.