How to Create a Form in Django: Simple Guide with Example
To create a form in Django, define a class that inherits from
django.forms.Form or django.forms.ModelForm in your forms.py. Then use this form in your views to render HTML and handle user input safely.Syntax
In Django, you create a form by defining a class that inherits from forms.Form or forms.ModelForm. Inside the class, you declare fields like CharField or EmailField to specify the input types.
For example, a simple form class looks like this:
python
from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea)
Example
This example shows a complete Django form setup with a form class, a view to handle the form, and a template to display it. The form collects a user's name, email, and message, validates input, and shows a success message on submission.
python/html
# forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea) # views.py from django.shortcuts import render from .forms import ContactForm def contact_view(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Process form data here (e.g., send email) return render(request, 'success.html') else: form = ContactForm() return render(request, 'contact.html', {'form': form}) # contact.html (template) """ <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form> """ # success.html (template) """ <p>Thank you for your message!</p> """
Output
<form method="post">
<p><label for="id_name">Name:</label> <input type="text" name="name" maxlength="100" required id="id_name"></p>
<p><label for="id_email">Email:</label> <input type="email" name="email" required id="id_email"></p>
<p><label for="id_message">Message:</label> <textarea name="message" cols="40" rows="10" required id="id_message"></textarea></p>
<button type="submit">Send</button>
</form>
Common Pitfalls
- Forgetting to include
{% csrf_token %}in your form template causes security errors. - Not calling
form.is_valid()before processing data can lead to invalid input handling. - Using
forms.Formwhen you want to save data to the database instead offorms.ModelForm. - Not passing
request.POSTto the form on POST requests results in empty forms.
html/python
## Wrong way (missing csrf_token and not validating form): """ <form method="post"> {{ form.as_p }} <button type="submit">Send</button> </form> """ # In view: form = ContactForm() # No form.is_valid() check ## Right way: """ <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form> """ # In view: form = ContactForm(request.POST) if form.is_valid(): # process data
Quick Reference
Here is a quick summary of key points when creating forms in Django:
| Step | Description |
|---|---|
| Define form class | Create a class inheriting from forms.Form or forms.ModelForm with fields. |
| Use form in view | Instantiate form with request.POST on POST, check form.is_valid(). |
| Render form in template | Use {{ form.as_p }} and include {% csrf_token %} inside |
| Process data | Access cleaned data via form.cleaned_data after validation. |
| Handle errors | Display form.errors in template to show validation messages. |
Key Takeaways
Create forms by defining classes inheriting from django.forms.Form or ModelForm.
Always validate form data with form.is_valid() before processing.
Include {% csrf_token %} in your form templates for security.
Pass request.POST to the form on POST requests to bind user input.
Use form.cleaned_data to access validated input safely.