13.8. Creating a Django Project: Forms and Validation

Página 66

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:

{% 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.

Next page of the Free Ebook:

6713.9. Creating a Django Project: Authenticating Users

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text