About Lesson
Built-in Validation
Django forms come with built-in validation. For example:
CharField
: Validates that the input is a string.EmailField
: Ensures the input is a valid email address.required
: By default, fields are required. You can setrequired=False
for optional fields.
Custom Validation
You can add custom validation logic for fields by overriding the clean_<fieldname>
method in the form:
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
def clean_name(self):
name = self.cleaned_data['name']
if "badword" in name:
raise forms.ValidationError("Name contains inappropriate words.")
return name
Form Errors
Form errors are displayed in the template like this:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
- {{ error }}
{% endfor %}
{% endfor %}
{% endif %}