Django Forms
Forms in Django:
Guide to working with forms in Django:
Creating HTML forms using Django forms:
Django provides a convenient way to generate HTML forms using Python classes called form classes.
You define these classes in your application's forms.py file.
Let's create a simple form for a contact page:
# 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)
In this example, we define a form called "ContactForm" with three fields: name, email, and message.
Form validation and error handling:
Django's form classes come with built-in validation.
When a form is submitted, Django automatically validates the data based on the field types and constraints defined in the form class.
To validate the forms in the view, just instantiate the form class with the data from the submitted form and call the “is_valid()” method.
Should the data is valid, you just need to process it, otherwise, Django displays error messages that you can display on a template.
# 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 the form data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# Additional processing or saving to the database
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
Processing form data in views:
Part of the 'view' function for a form is to handle both the GET and POST requirements.
For GET requests, you pass the form to be shown to templates by creating an instance of the form.
Then, considering POST requests, you validate submitted data by is_valid() function, and if it's correct, you can use cleaned_data attribute in order to access the cleaned's data.
<!-- contact.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
In the template, you can render the form fields using the {{ form.as_p }} template tag, which displays each field as a paragraph element (<p>).