Django Login and Logout Tutorial
Django login : In this lesson, we’ll learn how to set up Django’s built-in user authentication mechanism for login and logout capabilities.
This is the first in a three-part series that covers signup and password reset to provide your future Django applications with a comprehensive user authentication flow.
This guide will presume that you already know how to set up a new Django project. Please consult Django for Beginners, which goes into greater detail on the subject, if you need assistance.
Overview
On top of the session structure mentioned in the introductory course, Django offers an authentication and authorization (“permission”) system that enables you to validate user credentials and specify what actions each user is permitted to carry out.
The framework has built-in models for Users and Groups (a general method of granting permissions to multiple users simultaneously), permissions/flags that specify whether a user is allowed to complete a task, forms, and views for user login, and view tools for limiting content.
This lesson will teach you how to add permissions to your models, enable user authentication on the LocalLibrary website, construct your own login and logout pages, and manage page access.
We will present lists of books that have been checked out for users and librarians using authentication and permissions.
The given API can be used to log in users, and the authentication system is entirely configurable, allowing you to create URLs, forms, views, and templates from scratch if you’d like.
For our login and logout pages in this tutorial, we will use Django’s “stock” authentication views and forms. There are still some templates we need to make, but it’s pretty easy.
You’ll learn how to create permissions and check the status of your login and your permissions in both views and templates.
Setup
Create a new Django project first. Anywhere on your machine can host this code. The desktop is a handy location on a Mac, so that’s where we’ll put this code. From the command line, we may perform all of the standard configurations:
- create a new django_auth directory for our code on the Desktop
- create a new virtual environment called .venv and activate it
- install Django
- create a new Django project called django_project
- create a new Sqlite database with migrate
- run the local server
Here are the commands to run:
# Windows
> cd onedrive\desktop\
> mkdir django_auth
> cd django_auth
> python -m venv .venv
> .venv\Scripts\Activate.ps1
(.venv) > python -m pip install django~=4.0.0
(.venv) > django-admin startproject django_project .
(.venv) > python manage.py migrate
(.venv) > python manage.py runserver
# macOS
% cd ~/desktop/
% mkdir django_auth
% cd django_auth
% python3 -m venv .venv
% source .venv/bin/activate
(.venv) % python3 -m pip install django~=4.0.0
(.venv) % django-admin startproject django_project .
(.venv) % python manage.py migrate
(.venv) % python manage.py runserver
If you navigate to http://127.0.0.1:8000 you’ll see the Django welcome screen.

The Django auth app
When a new project is created, Django automatically downloads the authentication app. You can find one of the built-in applications Django has installed for us, auth, in the Django project/settings.py file under INSTALLED APPS.
# django_project/settings.py
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth", # Yoohoo!!!!
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
We must include the auth app in our project-level urls.py file to use it. On the second line, be sure to include the following. You can use any url pattern, but I’ve decided to place the auth app at accounts/.
# django_project/urls.py
from django.contrib import admin
from django.urls import path, include # new
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/", include("django.contrib.auth.urls")), # new
]
|
We now have access to several authentication views and URLs from the authentication app that manages login, logout, and password management.
The URLs that auth provides are:
accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']
|
Each URL pattern has related auth views as well. That implies all we need to do is make a template for each!
Login Page
Create our login page now! Django searches for auth templates in the templates folder under registration by default. Login.html is the name of the login template.
Please make a new directory named templates and one called registration inside of it.
(.venv) > mkdir templates
(.venv) > mkdir templates/registration
|
Then use your text editor to create a templates/registration/login.html file and insert the following code:
<!-- templates/registration/login.html -->
<h2>Log In</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log In</button>
</form>
|
This typical Django form sends data through POST and uses the security tags %csrf token% to guard against CSRF attacks. Form. as p’s output of the form’s contents within paragraph tags allows us to add a “submit” button.
The settings.py file should then be updated to instruct Django to look at the project-level templates folder. In TEMPLATES, change the DIRS setting as indicated below. One line has been changed.
# django_project/settings.py
TEMPLATES = [
{
...
'DIRS': [BASE_DIR / "templates"],
...
},
]
|
Our login capability now functions; however, we should indicate where to route the user after logging in successfully to improve it. In other words, where on the website should a user be directed after logging in?
To provide this path, we use the LOGIN REDIRECT URL setting. Add the following to the settings.py file’s bottom to lead users to the main page.
# django_project/settings.py
LOGIN_REDIRECT_URL = "/"
|
We’re done at this stage! The following will appear if you restart the Django server using python manage.py run server and go to our login page at http://127.0.0.1:8000/accounts/login/.
Create users
We haven’t yet made any users, so there’s one thing missing. Let’s rapidly create a superuser account from the command line. Run the command python manage.py to create a superuser after stopping the server by pressing Control+C.
Please answer the questions and take note that, for security purposes, your password won’t display on the screen as you type it.
(.venv) > python manage.py createsuperuser
Username (leave blank to use 'wsv'):
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.
|
Refresh the page at http://127.0.0.1:8000/accounts/login/ after restarting the server with python manage.py run server. Enter the login information for the user you just created.
Our login was successful because we were taken to the homepage, but as we have yet to establish it, we see the error Page not found. Fix that, then!
Create a homepage
We want a straightforward homepage that shows one message to users logged out and another to those logged in. Use your text editor to create the files templates/base.html and templates/home.html.
Note that these are not under templates/registration/, where Django auth looks by default for user auth templates but within the templates folder.
(.venv) $ touch templates/base.html
(.venv) $ touch templates/home.html
|
Add the following code to each:
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}Django Auth Tutorial{% endblock %}</title>
</head>
<body>
<main>
{% block content %}
{% endblock %}
</main>
</body>
</html>
|
<!-- templates/home.html -->
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
{% if user.is_authenticated %}
Hi {{ user.username }}!
{% else %}
<p>You are not logged in</p>
<a href="{% url 'login' %}">Log In</a>
{% endif %}
{% endblock %}
|
To extend our new base.html file, we can also alter login.html while we’re at it:
<!-- templates/registration/login.html -->
{% extends 'base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<h2>Log In</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log In</button>
</form>
{% endblock %}
|
Now modify urls.py so that we may see the homepage. Normally I would prefer to build a specific Pages app for this use, but because we don’t need it, we’ll add it to the Django project/urls.py file we already have.
On the third line, import TemplateView and add a pattern at the path “.”
# django_project/urls.py
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView # new
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('', TemplateView.as_view(template_name='home.html'), name='home'), # new
]
|
We’re done now. You may view the following if you restart the Django server with the command python manage.py run server and go to http://127.0.0.1:8000/:
It succeeded! How do we log out, though? There is now only one choice: enter the admin panel at http://127.0.0.1:8000/admin/ and select “Logout” from the menu in the top right.
This will log us out as seen by the redirect page:
We can notice we’ve logged out if you visit the homepage again at http://127.0.0.1:8000/ and refresh the page.
Changing passwords
On the user model, Django only stores hashes of passwords rather than their original, clear text form (see documentation of how passwords are managed for full details).
As a result, avoid manipulating the user’s password attribute. For this reason, a helper function is used while creating a user.
You have several alternatives when changing a user’s password.
manage.py Change a user’s password from the command line with change password *Username*. You are prompted to input the user’s current password twice while changing it.
The new passwords will be updated immediately if they are both the same. The program will attempt to update the password whose username matches the active system user if you do not give a user.
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username='john')
>>> u.set_password('new password')
>>> u.save()
|
On the admin pages for the authentication system, you can also modify user passwords if Django admin is installed.
Users can reset their passwords by using the views and forms that Django offers.
A user’s session will end when their password is changed. For further information, see Session invalidation on password change.
Authenticating users
authenticate(request=None, **credentials)
To validate a set of credentials, use authenticate(). It accepts credentials as keyword arguments—username and password by default—and verifies them with each authentication backend before returning a User object if they are.
It returns None if the credentials are invalid for any backend or if a backend raises PermissionDenied. For instance:
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
# A backend authenticated the credentials
else:
# No backend authenticated the credentials
|
The authenticate() method of the authentication backends accepts a request, an optional HttpRequest.
Logout link
Let’s include a logout link so people can quickly switch between our page’s two statuses. Fortunately, we already have a built-in url and view for this in the Django auth app. And if you stop to think about it, there is no need for a template as we don’t need to display anything upon logout.
After a successful “logout” request, all we do is reroute the user to another page.
So let’s first update our home.html file with a link to the built-in logout url:
<!-- templates/home.html-->
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
{% if user.is_authenticated %}
Hi {{ user.username }}!
<p><a href="{% url 'logout' %}">Log Out</a></p>
{% else %}
<p>You are not logged in</p>
<a href="{% url 'login' %}">Log In</a>
{% endif %}
{% endblock %}
|
Then add our redirect link, called LOGOUT REDIRECT URL, to settings.py. Add it immediately after our login redirect so that the settings.py file’s bottom line reads as follows:
# django_project/settings.py
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/" # new
|
We should use the homepage view rather than the existing hardcoded method now that we have one. What is the name of our homepage’s url? Our Django project/urls.py file’s name for it is home and is as follows:
# django_project/urls.py
...
path("", TemplateView.as_view(template_name="home.html"), name="home"),
...
|
So we can replace “/” with home at the bottom of the settings.py file:
# django_project/settings.py
LOGIN_REDIRECT_URL = "home"
LOGOUT_REDIRECT_URL = "home"
|
You will now be sent to the new site, which features a “logout” link for users who are logged in if you return to the homepage and log in.
Clicking it takes you back to the homepage with a “login” link.
Hands-On with Django User Authentication
Okay!! Enough reading; it’s time to start working with our hands.
Once a user logs in, we should have something to display. Therefore, let’s develop a basic View and template.
1) Code for Sample View
In the views.py file, insert the short BookView code.
from django.shortcuts import render
def books(request):
if request.user.is_authenticated:
return render(request, ‘itemsapp/books.html’)
else:
return redirect(‘/books/signin’)
|
2) Code for sample template
We’ll make a template for books that lists the following titles:
<h> Welcome to the Book Website</h>
<h2>List of Books</h2>
<ul><h3> The Prodigal Daughter</h3></ul><br>
<ul><h3> Deception Point</h3></ul><br>
<ul><h3> Washington Times</h3></ul><br>
<ul><h3> Sherlock Holmes</h3></ul><br>
<ul><h3> The Cooper Intrigue</h3></ul><br>
<a href = “{% url ‘logout’ %}”>Logout here</a>
|
3) Creating the Sign-up View
Add the code for the Sign-up View to Views.py.
from django.contrib.auth import authenticate,login
from django.contrib.auth.forms import UserCreationForm
def signup(request):
if request.user.is_authenticated:
return redirect(‘/books’)
if request.method == ‘POST’:
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data[‘username’]
password = form.cleaned_data[‘password1’]
user = authenticate(username = username,password = password)
login(request, user)
return redirect(‘/books’)
else:
return render(request,’itemsapp/signup.html’,{‘form’:form})
else:
form = UserCreationForm()
return render(request,’itemsapp/signup.html’,{‘form’:form})
|
The website’s sign-up form will look like this:
<form method =’post’>
{% csrf_token %}
{{form.as_p}}
<input type=”submit” value = “Submit”>
</form>
<h3>Already Have an Account??</h3>
<a href = “{% url ‘login’ %}”>Sign In Here</a>
|
4) Creating the Sign-in View
Add the following Sign-in View to your views now beneath the Sign Up View. py
from django.contrib.auth import authenticate,login
from django.contrib.auth.forms import AuthenticationForm
def signin(request):
if request.user.is_authenticated:
return redirect(‘/books’)
if request.method == ‘POST’:
username = request.POST[‘username’]
password = request.POST[‘password’]
user = authenticate(request, username =username, password = password)
if user is not None:
login(request,user)
return redirect(‘/books’)
else:
form = AuthenticationForm()
return render(request,’itemsapp/signin.html’,{‘form’:form})
else:
form = AuthenticationForm()
return render(request, ‘itemsapp/signin.html’, {‘form’:form})
|
The website’s sign-in template will look like this:
<form method = ‘post’>
{% csrf_token %}
{{form.as_p}}
<input type = “submit” value = “Submit”>
</form>
<h3>Dont have an account??</h3><br>
<a href = “{% url ‘signup’ %}”>SignUp Here</a>
|
5) Creating the Logout View
Finally, we will add the Log-out View code into the views.py file:
from django.contrib.auth import logout
def signout(request):
logout(request)
return redirect(‘/books/signin/’)
|
6) Mapping URLs to the Views
The URL paths for the Views coded in the above section will be:
path(‘books/signup/’, signup, name =’signup’),
path(‘books/signin/’, signin, name = ‘login’),
path(‘books/signout/’, signout, name = ‘logout’),
|
Conclusion
We have a strong login and logout authentication mechanism with very minimal code. Since the auth software accomplished most of the labor-intensive work for us, it seems magical.
Django’s ability to be customized, in addition to offering a lot of capability out-of-the-box, is one of its nicer features.
FAQs
Q.1 How to do a login in Django?
- Create the register form.
- Create a register.html file.
- Add a register URL to the app.
- Add a register function to the views.
- Test the register user functionality.
Q.2 How to login in Django admin?
ANS. Open the /admin URL (for example, http://127.0.0.1:8000/admin) to log in to the website. After entering your new superuser user id and password, you’ll be taken to the login screen and then back to the /admin URL.
Q.3 How to connect login page with database in Django?
ANS. The class-based view LoginView is used in Django applications to allow user logins. Add the following path to your accounts/urls.py file: URL patterns = [path(‘login/,’ views. LoginView.
Q.4 What is Django admin log?
ANS. The Django framework automatically creates log entries when users add, modify, or delete items using the admin interface.
With the help of the Django Admin Logs package, you can either examine the admin log entries directly from the admin interface or completely turn them off.
Q.5 How to write Django login form?
ANS. importing authenticate, login, and my view(request) from django.contrib.auth: Request = username. Request = POST[‘username’] password POST[‘password’] Authenticate(request, username=username, password=password), user = if the user is None: login(request, user) (request, user) # Direct traffic to a success page; otherwise: # Send back a “invalid”

My self Anjali Thakor, And I am a part-time blogger writing is my passion. I am writing articles on this blog about tech, finance, and many more where people can get updated information about daily life hacks, updated about technology, and many more. If you have any questions you can contact me.