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.
authenticate() to verify credentials and login()
to create an authenticated session.
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
A Django login system commonly uses several authentication components.
authenticate()login()logout()request.userlogin_required
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.
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.
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.
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>
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.
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.
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"
>
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"
>
Use authenticate() to verify the supplied credentials.
user = authenticate(
request,
username=username,
password=password
)
If authentication succeeds, Django returns a user object.
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.
After successful authentication, call login().
from django.contrib.auth import login
login(
request,
user
)
This associates the authenticated user with the current session.
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.
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"
)
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.
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.
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.
Set the login URL in settings.py when needed.
LOGIN_URL = "/login/"
This tells authentication redirects where the login page is located.
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.
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.
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.
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 %}
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.
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()
authenticate().login() without a valid user.{% csrf_token %}.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
<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>
A Django login system can be created using the built-in authentication framework.
authenticate() to verify credentials.login() after successful authentication.login_required for protected views.request.user to access the current user.authenticate() verifies login credentials.login() creates the authenticated session.request.user provides the current user.login_required protects private views.{% csrf_token %} in internal POST forms.Question: Which Django function is used to authenticate a username and password?