Django Form Validation: Complete Guide
In Django, handling form validation typically involves using Django’s form class and view functions. Initially, you need to define a form class that extends from Django’s forms.Form class, and define form fields and validation rules. Then, in the view function, you would receive the user-submitted form data and instantiate the form class for validation.
Here is a straightforward example:
# forms.py
from django import forms
class MyForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def clean_username(self):
username = self.cleaned_data['username']
# 自定义验证规则
if not username.isalnum():
raise forms.ValidationError("用户名只能包含字母和数字")
return username
# views.py
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():
# 处理表单数据
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# 其他操作...
else:
# 表单验证失败
return render(request, 'my_template.html', {'form': form})
else:
form = MyForm()
return render(request, 'my_template.html', {'form': form})
In the view function, the first step is to check if the request method is POST. If it is, then instantiate the form class and call the is_valid() method to validate it. If the form validation is successful, then you can access the validated data using the cleaned_data attribute for further processing. If the form validation fails, then return the form with error messages to prompt the user to fill it out again.
In the template, you can display error messages for both fields and non-field errors using form.errors and form.non_field_errors.
The above is an example of simple form validation processing, in actual applications, more complex form validation processes may be implemented according to specific requirements.