Working with Forms in Django: Collecting User Input Made Easy
Forms are essential for any web application that interacts with users — whether for login, registration, surveys, or data entry. Django’s built-in form system makes handling forms straightforward and secure.
Let’s explore how to create and use forms in Django!
️ What Is a Django Form?
A form in Django is a class that describes the fields you want to display to users and validates the submitted data.
Creating a Simple Form
You can define a form in forms.py
inside your app folder:
️ Displaying the Form in a Template
In your view, instantiate the form and send it to the template:
In contact.html
:
{{ form.as_p }}
renders all form fields wrapped in <p>
tags.
Handling Form Submission
To process submitted data, update your view:
-
form.is_valid()
checks if submitted data passes validation. -
Valid data is accessible via
form.cleaned_data
.
️ CSRF Protection
Always include {% csrf_token %}
inside your form to protect against cross-site request forgery attacks.
Model Forms: Forms Tied to Models
For forms that create or update database records, Django provides ModelForms:
This auto-generates form fields based on the model.
Summary
Step | Code Example |
---|---|
Define a form | class ContactForm(forms.Form): ... |
Display form | {{ form.as_p }} in template |
Process submission | if form.is_valid(): ... in view |
Use ModelForm | class BookForm(ModelForm): ... |