Lesson 45 of 60 – Django Login System
75%

Django Login System

A login system allows registered users to enter their username and password and access protected areas of a Django application.

Django provides built-in authentication functions that make it easier to create a secure login system.

Note: A typical Django login system uses authenticate() to verify credentials and login() to create an authenticated session.

1. What is a Login System?

A login system allows an existing user to prove their identity by entering valid login credentials.

A basic login process looks like this:

Username
   +
Password
   ↓
Check Credentials
   ↓
Login Successful
   ↓
Dashboard

2. Django Authentication Components

A Django login system commonly uses several authentication components.

  • User model
  • authenticate()
  • login()
  • logout()
  • Sessions
  • request.user
  • login_required

3. Importing Authentication Functions

The authentication functions can be imported from django.contrib.auth.

from django.contrib.auth import authenticate, login

These functions can then be used inside a login view.

4. Login URL

First, create a URL for the login page.

from django.urls import path
from . import views

urlpatterns = [

    path(
        "login/",
        views.login_view,
        name="login"
    ),

]

The name login can later be used with Django's URL reversing features.

5. Creating the Login View

The login view receives the username and password submitted by the user.

from django.shortcuts import render

def login_view(request):

    return render(
        request,
        "login.html"
    )

This is the basic starting point for a login page.

6. Creating the Login Template

Create a template such as login.html.

<h2>Login</h2>

<form method="post">

    {% csrf_token %}

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

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

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

</form>

7. Using POST Method

Login credentials should normally be submitted using the HTTP POST method.

<form method="post">

    ...

</form>

This allows the login view to process the submitted form data.

8. Checking the Request Method

The view can check whether the request is a POST request.

if request.method == "POST":

    # Process login data

    pass

For a GET request, the login form can simply be displayed.

9. Getting Username from the Form

Use request.POST.get() to retrieve the submitted username.

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

The name must match the HTML input field.

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

10. Getting Password from the Form

The password can also be retrieved from request.POST.

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

The HTML field should use the same name:

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

11. Using authenticate()

Use authenticate() to verify the supplied credentials.

user = authenticate(
    request,
    username=username,
    password=password
)

If authentication succeeds, Django returns a user object.

12. Checking Authentication Result

The result returned by authenticate() should be checked.

if user is not None:

    print("Valid login")

else:

    print("Invalid username or password")

A value of None indicates that authentication did not succeed.

13. Using login()

After successful authentication, call login().

from django.contrib.auth import login

login(
    request,
    user
)

This associates the authenticated user with the current session.

14. Redirecting After Login

After successful login, it is common to redirect the user to a dashboard.

from django.shortcuts import redirect

return redirect("dashboard")

The name must match a URL pattern defined in the project.

15. Complete Basic Login View

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login

def login_view(request):

    if request.method == "POST":

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

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

        user = authenticate(
            request,
            username=username,
            password=password
        )

        if user is not None:

            login(request, user)

            return redirect("dashboard")

        else:

            return render(
                request,
                "login.html",
                {
                    "error":
                    "Invalid username or password"
                }
            )

    return render(
        request,
        "login.html"
    )

16. Displaying Login Errors

The login page can display an error message when authentication fails.

{% if error %}

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

{% endif %}

This gives the user feedback when the supplied credentials are invalid.

17. CSRF Protection

Django provides CSRF protection for POST forms.

Include the CSRF token inside the login form:

<form method="post">

    {% csrf_token %}

    ...

</form>

This should be included in internal Django POST forms.

18. Protecting the Dashboard

After login, users may be redirected to a protected dashboard.

from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):

    return render(
        request,
        "dashboard.html"
    )

Users who are not authenticated are redirected according to the login configuration.

19. LOGIN_URL Setting

Set the login URL in settings.py when needed.

LOGIN_URL = "/login/"

This tells authentication redirects where the login page is located.

20. Redirecting Logged-in Users

A login view can redirect a user to another page after successful authentication.

if user is not None:

    login(request, user)

    return redirect("dashboard")

This creates a simple flow from login to dashboard.

21. Checking Logged-in User

The currently authenticated user can be accessed through request.user.

def dashboard(request):

    username = request.user.username

    return render(
        request,
        "dashboard.html",
        {
            "username": username
        }
    )

The username can then be displayed in the template.

22. Showing Username in Template

The authenticated user's username can be displayed directly in a template.

<h2>
Welcome, {{ request.user.username }}
</h2>

This can be useful for dashboards and account pages.

23. Login Link and Logout Link

A template can display different navigation links depending on whether the user is authenticated.

{% if user.is_authenticated %}

    <a href="/logout/">
        Logout
    </a>

{% else %}

    <a href="/login/">
        Login
    </a>

{% endif %}

24. Login with Django Built-in Views

Django also provides built-in authentication views that can be included using django.contrib.auth.urls.

from django.urls import include, path

urlpatterns = [

    path(
        "accounts/",
        include(
            "django.contrib.auth.urls"
        )
    ),

]

This provides standard authentication URL patterns, while the project supplies the required templates.

25. Password Authentication

Django's authentication system handles password verification through its password hashing system.

When creating or changing a password programmatically, use Django's password methods rather than assigning a raw password directly.

user.set_password(
    "newpassword"
)

user.save()

26. Common Login Errors

  • Forgetting to call authenticate().
  • Calling login() without a valid user.
  • Using incorrect input field names.
  • Forgetting {% csrf_token %}.
  • Incorrect login URL configuration.
  • Forgetting to include authentication-related applications.
  • Not running required migrations.
  • Not protecting private pages.
  • Using plain-text passwords.

27. Login Security Practices

  • Use Django's authentication system.
  • Never store plain-text passwords.
  • Use POST for login credentials.
  • Use CSRF protection for internal POST forms.
  • Protect private views with appropriate access checks.
  • Use HTTPS in production.
  • Use strong password policies where appropriate.
  • Do not expose passwords in URLs.

28. Complete Login Flow

User opens Login Page
        ↓
Enters Username
        ↓
Enters Password
        ↓
Submits POST Form
        ↓
login_view()
        ↓
authenticate()
        ↓
Valid User?
     ↙          ↘
   Yes           No
    ↓             ↓
 login()       Show Error
    ↓
Session Created
    ↓
Redirect
    ↓
Dashboard

29. Complete Login Template

<h2>User Login</h2>

{% if error %}

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

{% endif %}

<form method="post">

    {% csrf_token %}

    <label>Username</label>

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

    <br><br>

    <label>Password</label>

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

    <br><br>

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

</form>

30. Django Login System Summary

A Django login system can be created using the built-in authentication framework.

  • Create a login URL.
  • Create a login view.
  • Create a login form.
  • Accept the username and password through POST.
  • Use authenticate() to verify credentials.
  • Use login() after successful authentication.
  • Redirect the user to a protected page.
  • Use login_required for protected views.
  • Use request.user to access the current user.
  • Use Django's password handling instead of storing raw passwords.

📌 Key Points

  • Django provides a built-in authentication system.
  • authenticate() verifies login credentials.
  • login() creates the authenticated session.
  • request.user provides the current user.
  • login_required protects private views.
  • Login forms should normally use POST.
  • Use {% csrf_token %} in internal POST forms.
  • Django provides password hashing and password-management features.
  • Never store passwords as plain text.

🧠 Quick Quiz

Question: Which Django function is used to authenticate a username and password?