Skip to content
Python Guides
Python Guides
  • Learn Python
    • Start Here
    • Python Roadmap
    • Python Tutorials
    • Python Libraries
  • Machine Learning
    • ML Tutorials Hub
    • NumPy
    • Pandas
    • Matplotlib
    • Scikit-Learn
    • Tensorflow
    • Keras
    • PyTorch
  • Web Development
  • Downloads
    • Python Projects
    • FREE eBook
    • FREE Training Course
  • Blogs

How to Build a Login System in Python Django

Last Modified Date: July 23, 2025 by Bijay Kumar

Creating a login system is one of the foundational skills every web developer needs. I’ve built countless authentication systems, and Django’s built-in tools in my Python development journey make it surprisingly easy.

In this tutorial, I’ll walk you through building a simple yet robust login system using Python Django. By the end, you’ll have a working login, logout, and user authentication system tailored for real-world usage, like managing user accounts for a local USA-based business or community portal.

Table of Contents:

Toggle
  • Methods to Use Django for Your Login System?
    • Method 1: Use Django’s Built-In Authentication System
      • Step 1: Set Up Your Django Project
      • Step 2: Create User Login, Logout, and Dashboard Views
      • Step 3: Create URL Patterns
      • Step 4: Create HTML Templates
      • Step 5: Run Your Server and Test
    • Method 2: Custom Login System Without Django’s Built-in Views
      • Step 1: Custom Login Form
      • Step 2: Update Views to Use the Form
      • Step 3: Update Template to Render Form
  • Additional Tips from My Experience

Methods to Use Django for Your Login System?

Django is a useful Python web framework that comes with a built-in authentication system. This means you don’t have to reinvent the wheel when it comes to managing users, passwords, and sessions. The framework handles security best practices like password hashing and session management, so you can focus on building your app.

From my experience, Django’s built-in system is perfect for most projects because it balances ease of use with flexibility. You can customize it to fit your needs or extend it for more complex scenarios.

Read Create a Dictionary Application in Django

Method 1: Use Django’s Built-In Authentication System

This is the quickest and most reliable way to implement login functionality. Django provides views and forms out of the box, so you don’t have to write everything from scratch.

Step 1: Set Up Your Django Project

If you haven’t already, create a new Django project and app:

django-admin startproject myproject
cd myproject
python manage.py startapp accounts

Add the accounts app to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    ...
    'accounts',
]

Step 2: Create User Login, Logout, and Dashboard Views

In your accounts/views.py, add:

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages

def user_login(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:
            messages.error(request, 'Invalid username or password')
    return render(request, 'accounts/login.html')

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

def user_logout(request):
    logout(request)
    return redirect('login')

Step 3: Create URL Patterns

In accounts/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('login/', views.user_login, name='login'),
    path('dashboard/', views.dashboard, name='dashboard'),
    path('logout/', views.user_logout, name='logout'),
]

In your main myproject/urls.py include the accounts URLs:

from django.urls import path, include

urlpatterns = [
    path('accounts/', include('accounts.urls')),
]

Step 4: Create HTML Templates

Create a folder templates/accounts/ and add the following files:

login.html

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    {% if messages %}
        {% for message in messages %}
            <p style="color:red;">{{ message }}</p>
        {% endfor %}
    {% endif %}
    <form method="POST">
        {% csrf_token %}
        <label>Username:</label><br>
        <input type="text" name="username" required><br><br>
        <label>Password:</label><br>
        <input type="password" name="password" required><br><br>
        <button type="submit">Login</button>
    </form>
</body>
</html>

dashboard.html

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
</head>
<body>
    <h2>Welcome, {{ request.user.username }}</h2>
    <p>This is your dashboard.</p>
    <a href="{% url 'logout' %}">Logout</a>
</body>
</html>

Step 5: Run Your Server and Test

Create a superuser to test login:

python manage.py createsuperuser

Run the server:

python manage.py runserver

Visit http://127.0.0.1:8000/accounts/login/ and try logging in with the superuser credentials.

I executed the above example code and added the screenshot below.

django login system

Check out Django User Registration with Email Confirmation

Method 2: Custom Login System Without Django’s Built-in Views

Sometimes you want more control over the login process. Here’s a simplified example of how to build a custom login system without using Django’s default authentication views, but still leveraging the underlying authentication framework.

Step 1: Custom Login Form

Create a form in accounts/forms.py:

from django import forms

class LoginForm(forms.Form):
    username = forms.CharField(max_length=150)
    password = forms.CharField(widget=forms.PasswordInput)

Step 2: Update Views to Use the Form

Modify accounts/views.py:

from .forms import LoginForm

def user_login(request):
    form = LoginForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('dashboard')
        else:
            form.add_error(None, 'Invalid username or password')
    return render(request, 'accounts/login.html', {'form': form})

Step 3: Update Template to Render Form

Modify login.html:

<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Login</button>
</form>

This method gives you more flexibility to customize form validation and error handling.

I executed the above example code and added the screenshot below.

login system in Django

Read Python Django Import Functions

Additional Tips from My Experience

  • Always use Django’s @login_required decorator to protect views that require authentication.
  • Use Django’s messages framework to provide feedback to users on login success or failure.
  • For production, make sure to use HTTPS to secure user credentials.
  • Consider adding password reset and user registration features for a complete user management system.
  • For USA-based applications, you might want to add localization or timezone support depending on your user base.

Building a login system in Django doesn’t have to be complicated. Using Django’s built-in authentication system, you can get a secure login setup up and running quickly. For more control, you can customize forms and views to fit your specific needs.

If you follow the steps above, you’ll have a reliable login system ready to use in your Django projects. Feel free to expand on this foundation by adding features like user registration, email verification, and social authentication.

This tutorial is based on my hands-on experience and tailored to help developers in practical Django login systems efficiently. For more Django tutorials and Python guides, keep exploring PythonGuides.com.

You may like to read:

  • Python Django Convert Date Time to String
  • Register User with OTP Verification in Django
  • Create a Search Autocomplete with a Filter in Django
Bijay Kumar - Python and Machine Learning Expert
Bijay Kumar

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn

Generate Random Numbers in Python Django
Understand TypeScript Switch Statements

Recent Posts

  • Recursion in Python: A Complete Guide with Examples
  • Regular Expressions in Python (re Module Guide)
  • Python dir() Function: A Practical Guide With Examples
  • Python dict() Function: A Practical Guide With Examples
  • Python delattr() Function: Remove Object Attributes
  • About Us
  • Contact
  • Privacy Policy
  • Sitemap
© 2026 PythonGuides.com

Free PDF · 112 pages

Get the 51 Python Programs PDF

Tell me where to send it and the free 112-page PDF is on its way.

No spam. You'll also get new Python tutorials by email. Unsubscribe anytime. Privacy policy

Check your inbox

Your free 51 Python Programs PDF is on its way to . Can't find it in a few minutes? Look in your Promotions or Spam folder.