Django (9) - form processing

Django supports using classes to create form instances
polls/forms.py

from django import forms
class NameForm(forms.Form):
    your_name=forms.CharField(label="Your name",max_length=100)

This class creates a property that defines a text field, along with its label and maximum length.

polls/views.py

def name(request):
    #定义了一个form传给name.html模板,在模板中就不需要定义form的具体字段了
    form=NameForm()
    return render(request,"polls/name.html",{
    
    "form":form})

Define the name function in the view function, create an empty NameForm instance, and render this form instance to the form field of the template

template

In the template, you can directly use double quotes to refer to this form without defining the html input tag.

<form action=""{% url 'polls:yourname' %}" method="post">
    {% csrf_token %}
    {
   
   { form }}
    <input type="submit" value="Submit">
</form>

This template will render the instance from as shown below.
insert image description here

The form processing function passes the submitted data to the form, and uses the method is_valid() to verify the validity of the form. This method returns True
and puts the form's data into its attribute cleaned_data.

def get_name(request):
    if request.method=="POST":
        form=NameForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect("/thanks/")
    else:
        form=NameForm()
        return render(request,"name.html",{
    
    "form":form})

form = NameForm(request.POST) This is called "binding data to the form" (now it's a bound form).
The validated form data will be put into the form.cleaned_data dictionary. The data here has been nicely converted to Python types for you.
You can get the value directly from the form: subject = form.cleaned_data[“subject”]
Of course, you can also get the value directly from request.POST, but it is not recommended, because such data has not been verified.

Using forms in Django is a handy way to handle user input and data validation. Here are the general steps for using forms in Django:

  1. Define the form class: In your Django application, create a class to represent the form. This class usually inherits from django.forms.Formthe class and defines the fields that the form needs to contain.
from django import forms

class MyForm(forms.Form):
    field1 = forms.CharField(max_length=100)
    field2 = forms.EmailField()
    # 添加其他字段...
  1. Create a form instance: In the view function that needs to display the form, create an instance of the form and pass it to the template.
def my_view(request):
    form = MyForm()
    return render(request, 'my_template.html', {
    
    'form': form})
  1. Write an HTML template: Create a template to display the form and insert the HTML code for the form fields in the appropriate places.
<form method="post" action="{% url 'my_form_url' %}">
    {% csrf_token %}
    {
   
   { form.as_p }}
    <button type="submit">提交</button>
</form>

Here form.as_pthe form can be rendered as HTML in paragraph form. You can also use the form.as_table, , form.as_uletc. methods to render the form.

  1. Processing form submission: In the view function that receives the form submission, the data submitted by the user needs to be processed for data validation and processing.
def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            # 处理表单数据...
            return HttpResponseRedirect('/success/')
    else:
        form = MyForm()
    return render(request, 'my_template.html', {
    
    'form': form})

In this example, we first check if the request method is POST, and then instantiate a form object with the data submitted by the user. We then call form.is_valid()to verify that the form data is valid. If the form data is valid, it can be processed, such as saved to the database or perform other operations. If the form data is invalid, you need to return a form with validation error information for the user to fill out again.

The above are the basic steps to use the form, and you can customize and expand it according to your own needs and business logic.

Guess you like

Origin blog.csdn.net/seanyang_/article/details/132540535