Django Forms
Django forms make it easy to handle user input. The forms.Form class lets you define fields, validate data, and render HTML โ all in one place.
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
Each field type maps to an HTML input. Django handles validation automatically based on the field type.
Form Fields and Types
Django provides many built-in field types for different kinds of data.
from django import forms
class EventForm(forms.Form):
title = forms.CharField(max_length=200)
date = forms.DateField()
capacity = forms.IntegerField(min_value=1)
description = forms.CharField(widget=forms.Textarea, required=False)
newsletter = forms.BooleanField(initial=True, required=False)
Use required=False to make fields optional. The widget argument controls how the field renders in HTML.
Validating Form Data
Call is_valid() to validate submitted data. If valid, cleaned data is available in form.cleaned_data.
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
return HttpResponse('Form submitted!')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
Always check is_valid() before accessing cleaned data. If the form is invalid, errors are available in form.errors.
Rendering Forms in Templates
Django provides shortcut methods to render forms as HTML.
form.as_p()
form.as_table()
form.as_ul()
In templates, you can render the entire form or iterate over individual fields for more control.
for field in form
field.label_tag
field
field.errors
Rendering fields individually lets you customize the layout and add CSS classes.
Handling Form Errors
When validation fails, Django populates form.errors with a dictionary of error messages.
if form.is_valid():
pass
else:
for field, errors in form.errors.items():
for error in errors:
print(f'{field}: {error}')
Errors are displayed alongside fields automatically when using form.as_p() or similar methods. You can also access non-field errors with form.non_field_errors().