Creating a Django Project: Forms and Validation

Capítulo 66

Estimated reading time: 4 minutes

+ Exercise
Audio Icon

Listen in audio

0:00 / 0:00

One of the main features of Django is the ability to create dynamic and efficient forms to collect and process user data. In this section of our course on creating systems with Python and Django, we'll learn how to create a Django project that involves creating forms and validating data.

13.8.1. Creating your first Django form

To get started, let's create a new file in our Django application called 'forms.py'. In this file, we're going to define our first Django form. Django provides a 'forms.Form' class that we can use as the basis for our forms. Here is an example of how we can define a simple form:

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 contact form with three fields: name, email and message. Each field is defined using a Django-specific field class, such as 'forms.CharField' or 'forms.EmailField'.

13.8.2. Rendering your form in the template

Once you've defined your form, you'll need to render it in a template so that users can interact with it. This can be done by passing an instance of your form to the template context and then using the 'form' template tag to render the form. Here is an example of how you can do this:

def contact(request):
    form = ContactForm()
    return render(request, 'contact.html', {'form': form})

And in the 'contact.html' template, you can render the form like this:

Continue in our app.
  • Listen to the audio with the screen off.
  • Earn a certificate upon completion.
  • Over 5000 courses for you to explore!
Or continue reading below...
Download App

Download the app

{% csrf_token %} {{ form.as_p }}

13.8.3. Processing form data

When a user submits a form, the form data is sent to the server as a POST request. You can access this data in Django using the 'request.POST' attribute. Here is an example of how you can process the form data in your view:

def contact(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 form data...
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})

13.8.4. Validating form data

One of the main advantages of using Django forms is that they can handle the data validation for you. When you call the 'is_valid()' method on a form, Django checks every field on the form to ensure that the submitted data is valid. If any of the fields are not valid, Django will add an error to the form that you can display in your template.

In addition to the standard validation checks provided by Django, you can also add your own custom validation checks. To do this, you can add a method to your form that starts with 'clean_' followed by the name of the field you want to validate. Here is an example:

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if "hotmail.com" in email:
            raise forms.ValidationError("Please use a different email address.")
        return email

In this example, we've added a custom validation check to the email field to ensure the user isn't using a Hotmail email address.

In summary, creating forms and validating data are essential parts of any web application. Fortunately, Django makes this process very easy with its powerful form features.

Now answer the exercise about the content:

What is one of the key Django features mentioned in the text?

You are right! Congratulations, now go to the next page

You missed! Try again.

Django is known for its robust capability to create dynamic and efficient forms. This feature allows developers to efficiently collect and process user data while also handling data validation, making user interactions with web applications seamless and reliable.

Next chapter

Creating a Django Project: Authenticating Users

Arrow Right Icon
Free Ebook cover System creation course with Python and Django complete
38%

System creation course with Python and Django complete

New course

176 pages

Download the app to earn free Certification and listen to the courses in the background, even with the screen off.