Django Form Handling: Complete Guide
Dealing with form data in Django typically involves the following steps:
- To define a form class: First, it is necessary to define a form class that inherits from Django’s Form class, which includes the fields to be collected and related validation rules.
from django import forms
class MyForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
- Create a form instance: Create a form instance in the view function and pass the data from the request to the form instance.
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.get('name')
email = form.cleaned_data.get('email')
else:
form = MyForm()
return render(request, 'my_template.html', {'form': form})
- Render form: Use Django’s template language in the HTML template to render the form.
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">提交</button>
</form>
- Process form data: In the view function, validated data can be accessed through form.cleaned_data, and then processed accordingly.
It is important to note that when handling form data, it is essential to ensure the validity of the data. This can be done by validating the form data using form.is_valid(). Additionally, Django offers various convenient form validation features such as field validation, form validation, and custom validation, which can be used based on specific requirements.