Django forms and user registration


Lesson 11 of 14 · Python for the web

In the previous lesson we learned how Django uses models and the database.

Now we will see how users can enter data through web forms.

Forms let users send data to a web application.

What is a Django form?

A form is an HTML element that lets users enter data on a web page.

An example of a simple HTML form:


<form method="post">

<input type="text" name="name">

<button type="submit">Send</button>

</form>

The Django forms system

Django has a special system for working with forms that makes validating data easier.

A form is defined in the file forms.py.


from django import forms

class ContactForm(forms.Form):

    name = forms.CharField(max_length=100)

    message = forms.CharField(widget=forms.Textarea)

Django automatically checks whether the entered data is valid.

Displaying the form in a template

The form is displayed in an HTML template.


<form method="post">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Send</button>

</form>

Django uses CSRF protection to prevent attacks on the application.


Processing the form in a view function


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"]

    else:

        form = ContactForm()

    return render(request, "contact.html", {"form": form})
If the form is valid, Django gives us access to the data.

User registration

Django already has a built-in user authentication system.

This means we can easily make:

  • user registration
  • a login system
  • logout
  • profile management

An example of user registration


from django.contrib.auth.models import User

user = User.objects.create_user(
    username="mark",
    password="secret123"
)

This code creates a new user in the database.


The Django login page

Django makes it easy to add a login system to an application.


from django.contrib.auth import authenticate, login
User authentication is one of the most important features of web applications.

Related tutorials

If you want to see how a complete Django application works in practice, see the following tutorials:


Frequently asked questions

What is a Django form?

A Django form lets you enter and validate data.

What is a CSRF token?

A CSRF token protects the application from unauthorized requests.

Does Django have a system for users?

Yes. Django has a built-in system for authentication and user management.

Can we make a login system?

Yes. Django makes it easy to build login and registration pages.