Django Form usage

Django's Form is a class used to process form data. It allows you to define form fields as well as validation rules and process them when user-submitted data is received. The following are some basic concepts and usage methods about Django Form:

  1. Create a simple Form class
    First, you need to import the forms module, and then create a class that inherits from forms.Form. In this class, you can define various form fields and their validation rules.
from django import forms

class MyForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    age = forms.IntegerField()
    is_active = forms.BooleanField()

In the above example, we defined a simple form class MyForm, which contains string, email, integer and Boolean fields.

  1. Handling forms in views
    Generally, you would instantiate this form class in a Django view and pass it to the template on a GET request so that the user can fill out the form. On a POST request, you will instantiate the form with the user-submitted data, validate and process it.
from django.shortcuts import render
from .forms import MyForm

def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            # 处理有效的表单数据
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            # 进行其他操作...
    else:
        form = MyForm()

    return render(request, 'my_template.html', {'form': form})
  1. Rendering a form in a template In a
    template, you can use the template tags provided by Django to render form fields and display validation error messages.
<form method="post" action="{% url 'my_view' %}">
    {% csrf_token %}
    {
   
   { form.as_p }}
    <button type="submit">Submit</button>
</form>

The above { { form.as_p }} will render all fields of the form as

tag, you can also use other methods, such as { { form.as_table }} or { { form.as_ul }}.

  1. Form Validation
    In the above view code, we use form.is_valid() to check whether the form data is valid. Django will automatically execute the validation rules defined on the form fields and store the validated data in form.cleaned_data.

  2. Handling file uploads
    If your form contains a file upload field, you need to make sure to add enctype="multipart/form-data" to the form tag and use request.FILES in the view to handle the uploaded file.

<form method="post" action="{% url 'my_view' %}" enctype="multipart/form-data">
    <!-- 文件上传字段的定义 -->
    {
   
   { form.as_p }}
    <button type="submit">Submit</button>
</form>
def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():
            # 处理有效的表单数据,包括上传的文件
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            uploaded_file = request.FILES['uploaded_file']
            # 进行其他操作...
    else:
        form = MyForm()

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

This is the basic way to use forms in Django. Depending on your specific needs, you can also use Django's ModelForm, a more advanced form type for interacting with database models.

In Django, forms.Form and forms.ModelForm are two different classes used to handle forms. Their main difference lies in the way they process data and the scenarios they are applicable to.

forms.Form:

forms.Form is a basic form class used to handle any type of form data.
When defining the forms.Form class, you need to manually define its type and validation rules for each field.
This type of form is typically used to handle data that is not a database model, such as search forms, contact forms, etc.

from django import forms

class UserForm(forms.Form):
    username = forms.CharField(max_length=100)
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)

forms.ModelForm:

forms.ModelForm is a special type of form used for handling form data associated with a database model.
When you have a Django model (such as a table in a database) and want to create a form for adding, deleting, or modifying the model, you usually use forms.ModelForm.
It automatically generates corresponding form fields based on model fields, simplifying form definition.

from django import forms
from .models import UserProfile

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['username', 'email', 'password']

Here, the UserProfileForm class is derived from the UserProfile model and the Meta class defines the model to use and the fields to include.

Overall, forms.ModelForm is better suited for use with database models because it provides a more concise, automated way to define form fields. Forms.Form is more general and suitable for various situations, especially when you need to manually define form fields.

Guess you like

Origin blog.csdn.net/liulanba/article/details/134550861