Handling Form Submissions with POST

Tutorial 2 of 5

Handling Form Submissions with POST in Django

1. Introduction

In this tutorial, we will explore how to handle form submissions using the POST method in Django. We will cover capturing user input, validating the input data, and processing it using Django's form handling mechanisms.

By the end of this tutorial, you should be able to create a form on your Django website, capture user input, validate the input, and process the form submissions.

Prerequisites:
- Basic understanding of Python
- Familiarity with Django
- A Django project set up and ready to go

2. Step-by-Step Guide

In Django, we handle form submissions using Django's Form class. We'll create a form, capture user input in a view, validate the input, and then process the form submissions.

  1. Creating a Form: Create a forms.py file in your app directory if it doesn't exist. In this file, we'll define our form.

  2. Form Views: In your views.py file, we'll create a view to display the form and a view to handle the form submission.

  3. Form Templates: In your templates, we'll create a form display that users can interact with.

  4. Form Validation and Processing: Back in your views.py file, we'll handle the form validation and processing.

3. Code Examples

Let's go through these steps in detail with code examples.

  1. Creating a 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 the above code, we have created a ContactForm with three fields: name, email, and message.

  1. Form Views:
from django.shortcuts import render
from .forms import ContactForm

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 data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/')

    else:
        form = ContactForm()

    return render(request, 'name_of_your_template.html', {'form': form})

In the above code, we handle both GET and POST requests. If the request method is POST, we validate the form and process the data. Otherwise, we simply render the form.

  1. Form Templates:
<form method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

In the above code, we have created a form in our template. The {% csrf_token %} is a security feature of Django that you should always include in your forms.

  1. Form Validation and Processing:

This is handled in the view code already above.

4. Summary

In this tutorial, we covered how to handle form submissions using the POST method in Django. We learned how to create a form using Django's Form class, how to display the form in a template, and how to validate and process the form submission in a Django view.

Next steps for learning include exploring Django's ModelForm class, which is useful for creating forms that interact with your database models, and learning more about form validation.

Additional resources:

  • Django documentation on forms: https://docs.djangoproject.com/en/3.2/topics/forms/
  • Django for Beginners: https://djangoforbeginners.com/

5. Practice Exercises

  1. Create a form that captures a user's first name, last name, and email. Validate the form submission in a Django view.

  2. Modify the form you created in exercise 1 to also capture a user's age. Validate that the user's age is a number between 1 and 120.

  3. Create a form that captures a user's username and password. Validate the form submission in a Django view.

Solutions:

  1. This is similar to the example we went through in the tutorial.
  2. You will need to use Django's IntegerField and validators for this exercise.
  3. This is similar to exercise 1, but you will need to use Django's PasswordInput widget for the password field.

Remember to practice and experiment on your own to solidify your understanding. Happy coding!