Paramclasses Academy - Blog

Tutorials Details

Django Authentication and User Login System: Registration, Login, Logout, and Access Control

Django Authentication and User Login System: Registration, Login, Logout, and Access Control

October 19, 2026

Django Authentication and User Login System: Registration, Login, Logout, and Access Control

1. Introduction to Django Authentication

Authentication is an important part of almost every web application. It allows users to register, log in, log out, and access pages according to their permissions.

For example, in a Student Management System, students may access their profiles, while administrators may manage student records.

Django provides a built-in authentication system that includes:

  • User accounts and password hashing

  • Login and logout functionality

  • User registration components

  • Session management

  • Password change and reset functionality

  • Authentication and permission checks

In this module, you will build a basic authentication system using Django's built-in tools.

2. Authentication vs Authorization

Authentication answers the question: Who are you?

Example: A user logs in using a username and password.

Authorization answers the question: What are you allowed to do?

Example: A student can view their own profile, while an administrator can manage all student records.

Both concepts are necessary for building secure applications.

3. Create an Accounts App

Open your terminal in the Django project directory and run:

python manage.py startapp accounts

Open settings.py and add the app to INSTALLED_APPS:

INSTALLED_APPS = [
    # Existing Django apps...
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    # Custom app
    "accounts",
]

Keep your existing installed apps. Add accounts rather than replacing the complete list.

Django's authentication and session applications are included in a standard project created using startproject.

Run migrations if they have not already been applied:

python manage.py migrate

4. Create a Superuser

A superuser can access the Django administration site and manage users.

Run:

python manage.py createsuperuser

Follow the prompts to enter a username, email address if requested, and password.

Start the development server:

python manage.py runserver

Open:

http://127.0.0.1:8000/admin/

Log in using your superuser credentials.

Do not use weak passwords or share administrator credentials with ordinary users.

5. Create a User Registration Form

Django provides UserCreationForm, which supports creating users with password validation and password confirmation.

Open accounts/views.py and add:

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages

def register_view(request):
    if request.user.is_authenticated:
        return redirect("dashboard")

    if request.method == "POST":
        form = UserCreationForm(request.POST)

        if form.is_valid():
            form.save()
            messages.success(
                request,
                "Your account has been created successfully."
            )
            return redirect("login")
    else:
        form = UserCreationForm()

    return render(
        request,
        "accounts/register.html",
        {"form": form}
    )

This view performs the following steps:

  1. Checks whether the visitor is already logged in.

  2. Displays the registration form when the request is GET.

  3. Processes the submitted form when the request is POST.

  4. Validates the username and password.

  5. Saves the user if the form is valid.

  6. Redirects the user to the login page.

Django stores passwords using its password-hashing system rather than saving the raw password directly.

6. Create the Registration Template

Create this file:

templates/accounts/register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Account</title>
</head>
<body>
    <h1>Create Your Account</h1>

    {% if messages %}
        {% for message in messages %}
            <p>{{ message }}</p>
        {% endfor %}
    {% endif %}

    <form method="post">
        {% csrf_token %}

        {{ form.as_p }}

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

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

The {% csrf_token %} tag protects the form against cross-site request forgery (CSRF) attacks when used with Django's standard CSRF middleware.

{{ form.as_p }} displays the form fields inside paragraph elements. You can later customize the layout using HTML and CSS.

7. Configure Django's Built-In Login View

Django provides LoginView, which handles the login form and authenticates users.

Create or update accounts/urls.py:

from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views

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

    path(
        "login/",
        auth_views.LoginView.as_view(
            template_name="accounts/login.html"
        ),
        name="login"
    ),

    path(
        "logout/",
        auth_views.LogoutView.as_view(),
        name="logout"
    ),

    path(
        "dashboard/",
        views.dashboard_view,
        name="dashboard"
    ),

    path("", include("django.contrib.auth.urls")),
]

The final include("django.contrib.auth.urls") also provides Django's standard authentication URL patterns, including password-change and password-reset routes. Avoid defining conflicting URL patterns with the same names.

Now connect the app's URLs to the main project.

Open the main project's urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("accounts.urls")),
]

Your authentication pages will use URLs such as:

  • Registration: /accounts/register/

  • Login: /accounts/login/

  • Logout: /accounts/logout/

  • Dashboard: /accounts/dashboard/

8. Create the Login Template

Create:

templates/accounts/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Login</title>
</head>
<body>
    <h1>Login to Your Account</h1>

    {% if form.errors %}
        <p>Invalid username or password. Please try again.</p>
    {% endif %}

    {% if next %}
        <p>Please log in to access the requested page.</p>
    {% endif %}

    <form method="post">
        {% csrf_token %}

        {{ form.as_p }}

        <input
            type="hidden"
            name="next"
            value="{{ next|default:'' }}"
        >

        <button type="submit">Login</button>
    </form>

    <p>
        Don't have an account?
        <a href="{% url 'register' %}">Register here</a>
    </p>

    <p>
        <a href="{% url 'password_reset' %}">
            Forgot your password?
        </a>
    </p>
</body>
</html>

LoginView uses Django's authentication form to validate credentials. When the credentials are valid, Django logs the user in and establishes the appropriate session.

9. Configure Login Redirects

Open your project's settings.py and add:

LOGIN_URL = "/accounts/login/"
LOGIN_REDIRECT_URL = "/accounts/dashboard/"
LOGOUT_REDIRECT_URL = "/accounts/login/"

These settings control the default login destination, the destination after successful login, and the destination after logout.

When using named URL patterns, you can also use Django's reverse_lazy() where supported by the setting or view configuration.

10. Create a Protected Dashboard

Open accounts/views.py and add the following view below the registration view:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def dashboard_view(request):
    return render(
        request,
        "accounts/dashboard.html"
    )

The @login_required decorator prevents unauthenticated visitors from viewing the dashboard. Django redirects them to the configured login page.

Create:

templates/accounts/dashboard.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Dashboard</title>
</head>
<body>
    <h1>Welcome to Your Dashboard</h1>

    <p>
        Hello, {{ request.user.username }}!
    </p>

    <p>You are successfully logged in.</p>

    <form method="post" action="{% url 'logout' %}">
        {% csrf_token %}
        <button type="submit">Logout</button>
    </form>
</body>
</html>

The dashboard displays the username of the authenticated user. The logout form uses POST and includes a CSRF token.

Important: In current Django versions, the built-in LogoutView handles logout through POST requests. Do not implement logout using an ordinary GET link.

11. How the Authentication Workflow Works

The complete workflow is:

  1. A visitor opens the registration page.

  2. The visitor submits the registration form.

  3. Django validates the submitted information.

  4. Django creates the user account.

  5. The user opens the login page.

  6. Django verifies the credentials.

  7. Django creates an authenticated session.

  8. The user accesses the protected dashboard.

  9. The user submits the logout form.

  10. Django ends the authenticated session and redirects the user.

This is a simplified workflow suitable for learning. Production systems may require email verification, rate limiting, account recovery controls, and other protections.

12. Password Reset and Change

Django's built-in authentication URL patterns include routes for password reset and password change.

The password-reset workflow normally requires:

  • A password-reset request form

  • An email address associated with the account

  • A configured email backend

  • Reset email and confirmation templates

  • A valid, time-limited reset link

For local development, you can configure Django to print outgoing emails to the terminal:

EMAIL_BACKEND = (
    "django.core.mail.backends.console.EmailBackend"
)

This is for development only. For a real deployment, configure a trusted email service and protect its credentials.

Django's built-in password-change views also support changing the password for an authenticated user. You can customize their templates to match your website design.

13. Authentication Security Best Practices

Follow these practices when building a real application:

  1. Never store passwords as plain text.

  2. Always include CSRF protection in POST forms.

  3. Use HTTPS in production.

  4. Restrict private pages using authentication and authorization checks.

  5. Do not expose secret keys or email-service credentials in public repositories.

  6. Use strong passwords and Django's password validators.

  7. Apply login rate limiting where appropriate to reduce brute-force attempts.

  8. Keep Django and its dependencies updated.

  9. Do not assume that hiding a button makes an operation secure; validate permissions on the server.

  10. Use secure cookie and session settings for production.

14. Common Errors and Solutions

Error 1: TemplateDoesNotExist

Check that your templates exist at the paths used by the views. If you use a project-level templates directory, configure TEMPLATES in settings.py appropriately.

Error 2: NoReverseMatch

Ensure that URL names such as login, logout, register, and dashboard match the names declared in your URL configuration. Be careful when including authentication URLs that define names already used elsewhere.

Error 3: Login redirects to the wrong page

Check LOGIN_REDIRECT_URL, the optional next parameter, and any custom redirect logic.

Error 4: CSRF verification failed

Ensure the template contains {% csrf_token %} inside the POST form and that Django's CSRF middleware is enabled.

Error 5: Login always fails

Check the username and password, verify that the user exists, and confirm that the account is active.

Error 6: Dashboard opens without login

Make sure the view uses @login_required or an appropriate authentication mixin, and confirm that the route points to the protected view.

Error 7: Logout returns Method Not Allowed

Submit the logout form using POST and include {% csrf_token %}.

15. Frequently Asked Questions

Q1. What is Django authentication?

It is Django's system for identifying users and managing login sessions, passwords, and related authentication operations.

Q2. What is UserCreationForm?

It is Django's built-in form for creating users with password validation.

Q3. What is LoginView?

It is a generic view that handles login form display and credential authentication.

Q4. What is LogoutView?

It is Django's built-in view for ending an authenticated session.

Q5. What does login_required do?

It restricts a view to authenticated users and redirects unauthenticated visitors to the login page.

Q6. Does Django store passwords in plain text?

No. Django uses password hashing to store passwords securely.

Q7. What is a session?

A session allows an application to maintain user-specific state across multiple HTTP requests.

Q8. Can Django support user roles?

Yes. Django provides groups and permissions, and developers can build additional role-based access rules when needed.

Q9. What is the purpose of LOGIN_URL?

It specifies the login destination used by authentication-protected views when an unauthenticated visitor needs to log in.

Q10. Is a login page enough to secure an application?

No. The server must enforce authentication and authorization for every protected operation and resource.

16. Interview Questions and Answers

Q1. Explain authentication and authorization.

Authentication verifies who a user is. Authorization determines which actions or resources the user is permitted to access.

Q2. What does authenticate() do?

Django's authenticate() function checks credentials using the configured authentication backends and returns a user object when authentication succeeds, or None otherwise.

Q3. What does login() do?

Django's login() function associates an authenticated user with the current session.

Q4. What does logout() do?

Django's logout() function clears the current session's authentication data.

Q5. Why is CSRF protection important?

It helps prevent unauthorized websites from causing a user's browser to submit unwanted requests to an authenticated application.

Q6. How do you protect a function-based view?

Use @login_required and add any required permission checks.

Q7. How can a class-based view require authentication?

A common approach is to use LoginRequiredMixin in the class's inheritance list, with the mixin placed before the generic view class.

Q8. How do you implement role-based permissions?

Use Django groups and permissions or carefully designed custom role logic, and enforce the checks on the server.

17. Practical Assignment

Build a complete basic authentication system for your Student Management project.

Requirements:

  1. Create an accounts app.

  2. Implement user registration with UserCreationForm.

  3. Build a login page using LoginView.

  4. Build a dashboard protected by login_required.

  5. Add logout using a POST form.

  6. Configure login and logout redirects.

  7. Add a password-reset link and configure the reset workflow.

  8. Display the authenticated user's username.

  9. Test invalid passwords, unauthenticated access, and logout behavior.

  10. Verify that private pages cannot be accessed simply by entering their URLs directly.

Bonus task: Create an administrator-only page and use Django's permission system to restrict access.

18. Conclusion

Django provides powerful built-in tools for user authentication, including registration forms, login and logout views, sessions, and password management.

Understanding authentication and authorization is essential before building applications with private dashboards, user profiles, administrator panels, or role-based access.

Practice the full registration-to-logout workflow before moving to the next module.

Next Module: Django Static Files, CSS, JavaScript, and Images — Building a Professional User Interface.