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

Django’s Built-in Login System

Last Modified Date: August 6, 2025 by Bijay Kumar

I’ve worked with numerous web frameworks as part of my projects. Django stands out for its robust built-in authentication system, which simplifies user login management without reinventing the wheel. If you’re building a web app or anywhere else, securing your application with Django’s built-in login system is essential.

In this article, I’ll walk you through how to set up and customize Django’s login system from scratch. Whether you’re new to Django or just want a refresher, this guide will help you implement a secure, user-friendly login system in your projects.

Let’s get in!

Table of Contents:

Toggle
  • Django’s Built-In Login System
  • Set Up the Django Project
    • Method 1: Use Django’s Default Authentication Views
      • Step 1: Configure URLs
      • Step 2: Create Templates for Login and Logout
      • Step 3: Configure Template Settings
      • Step 4: Set Login Redirect URL
      • Step 5: Create a Simple Home View
      • Step 6: Run Migrations and Create a Superuser
    • Method 2: Custom Login View Using Django’s AuthenticationForm
      • Step 1: Create a Custom Login View
      • Step 2: Update URLs
      • Step 3: Create Templates
      • Step 4: Adjust Settings
  • Additional Tips from My Experience

Django’s Built-In Login System

Django provides an out-of-the-box authentication framework that handles user registration, login, logout, password management, and permissions. This means you don’t need to build these features from scratch, saving you time and reducing security risks.

From my experience, using Django’s built-in system ensures you follow security best practices, such as password hashing and session management, without extra effort.

Check out Create a Card with a Button in Django

Set Up the Django Project

Let’s start by creating a new Django project and app. I’ll use an example relevant to a US-based e-commerce site called ShopUSA.

Open your terminal and run:

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

Next, add the accounts app to your INSTALLED_APPS in shopusa/settings.py:

INSTALLED_APPS = [
    # default apps...
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # our app
    'accounts',
]

Read Create a User Profile Using Django

Method 1: Use Django’s Default Authentication Views

Django comes with pre-built views for login and logout, which makes implementation quick and easy.

Step 1: Configure URLs

In your project’s main urls.py (shopusa/urls.py), include Django’s auth URLs:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
]

This includes several authentication-related URLs:

  • /accounts/login/ for login
  • /accounts/logout/ for logout
  • /accounts/password_change/ and others for password management

Step 2: Create Templates for Login and Logout

Django expects certain templates in the templates/registration/ directory.

Create the directory structure inside your project:

shopusa/
├── templates/
│   └── registration/
│       ├── login.html
│       └── logged_out.html

Here’s a simple login.html template:

<!-- templates/registration/login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login - ShopUSA</title>
</head>
<body>
    <h2>Login to ShopUSA</h2>
    {% if form.errors %}
        <p style="color:red;">Invalid username or password.</p>
    {% endif %}
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Login</button>
    </form>
</body>
</html>

And a simple logged_out.html:

<!-- templates/registration/logged_out.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Logged Out - ShopUSA</title>
</head>
<body>
    <h2>You have been logged out.</h2>
    <a href="{% url 'login' %}">Login again</a>
</body>
</html>

Step 3: Configure Template Settings

In settings.py, add the templates directory:

import os

TEMPLATES = [
    {
        # existing config...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        # rest unchanged
    },
]

Step 4: Set Login Redirect URL

After a successful login, Django redirects users to /accounts/profile/ by default. Let’s change it to the homepage.

Add this to settings.py:

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/accounts/login/'

Step 5: Create a Simple Home View

Create a basic homepage to test login redirection.

In shopusa/views.py:

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

@login_required
def home(request):
    return render(request, 'home.html')

In shopusa/urls.py, add:

from django.urls import path
from .views import home

urlpatterns = [
    path('', home, name='home'),
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
]

Create templates/home.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ShopUSA Home</title>
</head>
<body>
    <h1>Welcome, {{ user.username }}!</h1>
    <p>You are logged in.</p>
    <a href="{% url 'logout' %}">Logout</a>
</body>
</html>

Step 6: Run Migrations and Create a Superuser

Run the following commands:

python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

Navigate to http://127.0.0.1:8000/accounts/login/, log in with your superuser, and you’ll be redirected to the homepage.

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

django login
login django

Check out Create an API in Python Django

Method 2: Custom Login View Using Django’s AuthenticationForm

Sometimes, you want more control over the login process or template. You can create your login view.

Step 1: Create a Custom Login View

In accounts/views.py:

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

def custom_login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('home')
    else:
        form = AuthenticationForm()
    return render(request, 'accounts/login.html', {'form': form})

def custom_logout(request):
    logout(request)
    return redirect('custom_login')

Step 2: Update URLs

In accounts/urls.py:

from django.urls import path
from .views import custom_login, custom_logout

urlpatterns = [
    path('login/', custom_login, name='custom_login'),
    path('logout/', custom_logout, name='custom_logout'),
]

Include this in your project’s main URL config (shopusa/urls.py):

path('accounts/', include('accounts.urls')),

Step 3: Create Templates

Create templates/accounts/login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Custom Login - ShopUSA</title>
</head>
<body>
    <h2>Login to ShopUSA</h2>
    {% if form.errors %}
        <p style="color:red;">Invalid username or password.</p>
    {% endif %}
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Login</button>
    </form>
</body>
</html>

Step 4: Adjust Settings

Set the redirects in settings.py accordingly:

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/accounts/login/'

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

login python Django
login system in django

Read JWT Authentication Using Django Rest Framework

Additional Tips from My Experience

  • Use Django’s @login_required decorator to protect views that require authentication.
  • Always use HTTPS in production to secure user credentials.
  • Customize the User model early if you need extra fields like phone numbers or addresses.
  • Leverage Django’s password reset views to offer users a way to recover accounts.
  • Consider using third-party packages like django-allauth if you want social login integration.

Implementing Django’s built-in login system is easy and secure. Whether you use the default authentication views or create custom ones, Django’s framework provides flexibility to suit your project’s needs.

By following the steps above, you’ll have a reliable login system powering your web application, ready to serve users across the USA or anywhere globally. If you want to extend this further, consider adding registration, email verification, and password reset functionalities, all of which Django supports elegantly.

If you have any questions or want me to cover more Django topics, feel free to reach out!

Other Django articles you may also like:

  • File Upload in Django
  • How to Deploy an AI Model with Django
  • Build a Chat App 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

Django Google Authentication
Implement Captcha in Django 

Recent Posts

  • UnboundLocalError: Local Variable Referenced Before Assignment in Python
  • Python Variable Scope: Local, Global, Nonlocal and LEGB
  • Recursion in Python: A Complete Guide with Examples
  • Regular Expressions in Python (re Module Guide)
  • Python dir() Function: A Practical Guide With Examples
  • 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.