Lesson 47 of 60 – Django Registration System
78%

Django Registration System

A registration system allows new users to create accounts in a Django application. A typical registration form collects information such as username, email, and password.

Django provides a built-in User model and password-management system that can be used to create a secure user registration workflow.

Note: User registration normally involves validating the submitted data, creating the user with Django's password-handling methods, and then redirecting the user after successful registration.

1. What is User Registration?

User registration is the process of creating a new user account in a web application.

A basic registration flow looks like this:

User Opens Registration Page
        ↓
Enters User Details
        ↓
Form Validation
        ↓
Create User
        ↓
Registration Successful
        ↓
Login Page

2. Registration vs Login

Registration Login
Creates a new account. Accesses an existing account.
Usually happens once for an account. Can happen many times.
Stores new user information. Verifies existing credentials.

3. Django User Model

Django provides a built-in User model through its authentication system.

from django.contrib.auth.models import User

The User model can store commonly required account information such as username, email, password, and permission-related information.

4. Creating Users with create_user()

Django provides the create_user() method for creating users.

from django.contrib.auth.models import User

user = User.objects.create_user(
    username="rahul",
    email="rahul@example.com",
    password="secret123"
)

This method uses Django's password handling instead of storing the supplied password as plain text.

5. Registration URL

Create a URL pattern for the registration page.

from django.urls import path
from . import views

urlpatterns = [

    path(
        "register/",
        views.register_view,
        name="register"
    ),

]

6. Creating the Registration View

A registration view can display the form when the request is GET and process the form when the request is POST.

from django.shortcuts import render

def register_view(request):

    return render(
        request,
        "register.html"
    )

7. Registration Form

A simple registration form can contain username, email, and password fields.

<form method="post">

    {% csrf_token %}

    <input
        type="text"
        name="username"
        placeholder="Username"
    >

    <input
        type="email"
        name="email"
        placeholder="Email"
    >

    <input
        type="password"
        name="password"
        placeholder="Password"
    >

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

</form>

8. Using the POST Method

Registration data should normally be submitted using the POST method.

<form method="post">

    ...

</form>

The registration view can then process the submitted data.

9. Checking the Request Method

Use request.method to determine whether the form was submitted.

if request.method == "POST":

    # Process registration

    pass

For a GET request, the registration form can be displayed.

10. Getting Form Data

Use request.POST.get() to retrieve submitted values.

username = request.POST.get(
    "username"
)

email = request.POST.get(
    "email"
)

password = request.POST.get(
    "password"
)

The names must match the HTML form fields.

11. Checking Username Availability

Before creating a user, the application can check whether the username already exists.

if User.objects.filter(
    username=username
).exists():

    error = "Username already exists"

Usernames that must be unique should be validated before attempting to create the account.

12. Creating the User

After validating the submitted information, create the user with create_user().

user = User.objects.create_user(
    username=username,
    email=email,
    password=password
)

Django handles the password using its password hashing system.

13. Why Not Store a Plain Password?

Passwords should not be stored as plain text in the database.

Avoid code such as:

user.password = password

Instead, use Django's password-aware methods such as:

User.objects.create_user(
    username=username,
    password=password
)

14. Password Validation

Django provides password validation functionality that can be configured through the AUTH_PASSWORD_VALIDATORS setting.

These validators can help check passwords against configured rules such as common or weak passwords.

AUTH_PASSWORD_VALIDATORS = [
    ...
]

15. Basic Registration View

from django.shortcuts import render, redirect
from django.contrib.auth.models import User

def register_view(request):

    if request.method == "POST":

        username = request.POST.get(
            "username"
        )

        email = request.POST.get(
            "email"
        )

        password = request.POST.get(
            "password"
        )

        if User.objects.filter(
            username=username
        ).exists():

            return render(
                request,
                "register.html",
                {
                    "error":
                    "Username already exists"
                }
            )

        User.objects.create_user(
            username=username,
            email=email,
            password=password
        )

        return redirect("login")

    return render(
        request,
        "register.html"
    )

16. Confirm Password

Registration forms commonly ask users to enter their password twice.

<input
    type="password"
    name="password"
    placeholder="Password"
>

<input
    type="password"
    name="confirm_password"
    placeholder="Confirm Password"
>

The two values can then be compared before creating the account.

17. Checking Password Confirmation

password = request.POST.get(
    "password"
)

confirm_password = request.POST.get(
    "confirm_password"
)

if password != confirm_password:

    return render(
        request,
        "register.html",
        {
            "error":
            "Passwords do not match"
        }
    )

18. Checking Required Fields

Required fields should be validated before creating the user.

if not username or not email or not password:

    return render(
        request,
        "register.html",
        {
            "error":
            "All fields are required"
        }
    )

HTML required attributes can also improve the user experience, but server-side validation should still be performed.

19. Email Validation

An email field should contain a valid email address.

When using Django Forms, forms.EmailField can perform basic email-format validation.

from django import forms

class RegistrationForm(forms.Form):

    email = forms.EmailField()

20. Using Django Forms for Registration

For larger applications, Django Forms can make registration validation easier to manage.

from django import forms

class RegistrationForm(forms.Form):

    username = forms.CharField(
        max_length=150
    )

    email = forms.EmailField()

    password = forms.CharField(
        widget=forms.PasswordInput
    )

The form can then be validated using is_valid().

21. Registration with is_valid()

form = RegistrationForm(
    request.POST
)

if form.is_valid():

    username = form.cleaned_data[
        "username"
    ]

    email = form.cleaned_data[
        "email"
    ]

    password = form.cleaned_data[
        "password"
    ]

Using forms separates validation logic from the view.

22. Registration and CSRF Protection

A Django registration form submitted with POST should include the CSRF token.

<form method="post">

    {% csrf_token %}

    ...

</form>

Django uses CSRF protection to help protect internal POST requests.

23. Redirect After Registration

After successfully creating an account, redirect the user to another page.

return redirect("login")

This can send the new user to the login page.

Another option is to log the user in immediately and redirect them to a dashboard.

24. Automatically Logging in After Registration

A newly created user can be logged in immediately after registration.

from django.contrib.auth import login

user = User.objects.create_user(
    username=username,
    email=email,
    password=password
)

login(request, user)

return redirect("dashboard")

This provides a registration-to-dashboard workflow without requiring a second login step.

25. Registration with get_or_create()

Django provides get_or_create() for situations where you want to retrieve an existing object or create one when it does not exist.

user, created = User.objects.get_or_create(
    username=username
)

For normal registration, however, explicit validation and create_user() are often clearer because a new password and other account information must be handled.

26. Common Registration Mistakes

  • Storing passwords as plain text.
  • Not checking whether the username already exists.
  • Not validating required fields.
  • Not checking password confirmation.
  • Forgetting {% csrf_token %}.
  • Using GET for submitting passwords.
  • Not validating email addresses.
  • Ignoring Django's password handling.
  • Not displaying useful validation errors.
  • Creating users without handling possible validation or database errors.

27. Registration Security Practices

  • Use Django's password hashing system.
  • Use POST for registration forms.
  • Use CSRF protection.
  • Validate all submitted data on the server.
  • Use strong password policies where appropriate.
  • Do not expose passwords in URLs.
  • Use HTTPS in production.
  • Do not trust only browser-side validation.
  • Give users clear but safe error messages.

28. Complete Registration Flow

User Opens Registration
        ↓
Enter Username
        ↓
Enter Email
        ↓
Enter Password
        ↓
Confirm Password
        ↓
Submit POST Form
        ↓
Validate Data
        ↓
Username Available?
     ↙          ↘
   Yes           No
    ↓             ↓
Create User    Show Error
    ↓
Password Stored Securely
    ↓
Redirect/Login
    ↓
Dashboard

29. Complete Registration Template

<h2>Create Account</h2>

{% if error %}

<div>
    {{ error }}
</div>

{% endif %}

<form method="post">

    {% csrf_token %}

    <label>Username</label>

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

    <br><br>

    <label>Email</label>

    <input
        type="email"
        name="email"
        required
    >

    <br><br>

    <label>Password</label>

    <input
        type="password"
        name="password"
        required
    >

    <br><br>

    <label>Confirm Password</label>

    <input
        type="password"
        name="confirm_password"
        required
    >

    <br><br>

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

</form>

<p>
Already have an account?
<a href="{% url 'login' %}">
Login
</a>
</p>

30. Django Registration System Summary

Django provides the tools needed to create a user registration system without manually implementing password storage.

  • Use the Django User model for user accounts.
  • Use POST for registration data.
  • Use CSRF protection for internal POST forms.
  • Validate usernames, emails, and passwords.
  • Use create_user() to create users.
  • Never store passwords as plain text.
  • Use password confirmation when appropriate.
  • Use Django Forms for organized validation.
  • Redirect the user after successful registration.
  • Users can optionally be logged in immediately after registration.

📌 Key Points

  • Django provides a built-in User model.
  • User.objects.create_user() is used to create users with proper password handling.
  • Registration forms should normally use POST.
  • Use {% csrf_token %} in internal POST forms.
  • Always validate registration data on the server.
  • Check username availability before creating an account.
  • Password confirmation can help prevent typing mistakes.
  • Django Forms can simplify validation.
  • A successful registration can redirect to login or log the user in automatically.

🧠 Quick Quiz

Question: Which Django method should normally be used to create a user with a properly handled password?