In this tutorial, our main goal is to help you understand how to create and validate forms in Django using Django's Forms API. By the end of this tutorial, you will have a solid understanding of how to create forms, validate user input, and handle form submissions effectively.
What you will learn:
Prerequisites:
Django provides a powerful form library that handles rendering form HTML, validating user input, and converting those inputs into Python types.
A Django form is created by subclassing the forms.Form
class. Each attribute of the form class represents a field of the form.
Django form provides a is_valid()
method to perform form validation. This method checks if all the form fields have valid data.
When a form is submitted, Django will handle the form submission in a view. The form data will be validated and if the form is valid, the data will be processed.
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
In the above code, name
, email
, and message
are the fields of the form.
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']
# Process the data, send email, save to database, etc
return HttpResponseRedirect('/thanks/') # Redirect after successful handling
else:
form = ContactForm() # An empty form
return render(request, 'contact.html', {'form': form})
In this view, we first check if the request method is 'POST'. If it is, that means the form has been submitted. We then validate the form data with form.is_valid()
. If the form is valid, we can access the cleaned data and process it.
In this tutorial, we learned how to create forms in Django, validate form data, and handle form submissions.
Next steps for learning:
Additional resources:
Exercise 1: Create a Django form with the fields first_name
, last_name
, email
, phone_number
, and address
.
Exercise 2: Create a view to handle the form submission, validate the form data, and print the cleaned data to the console.
Exercise 3: Create a custom validation for the phone_number
field that checks if the phone number is valid.
Tips for further practice: