Django: How to authenticate a user

Learn how to authenticate a user in Django, using the built-in authentication form.

Photo by Towfiqu barbhuiya on Unsplash

How can we define authentication?

Authentication involves the process of proving that you are, who you say you are.

So, how do we integrate authentication in Django?

Step 1:

Create a form that inherits Django’s in-built authentication form.

Once we’ve imported our AuthenticationForm and attached it to our class LoginForm, we need to import a PasswordInput and TextInput widget so that users can input their username and password on our LoginForm.

We need to also ensure that we import forms so that we can make use of our widgets.

# - forms.pyfrom django.contrib.auth.forms import AuthenticationFormfrom django.forms.widgets import PasswordInput, TextInput
from django import forms
class LoginForm(AuthenticationForm): username = forms.CharField(widget=TextInput())
password = forms.CharField(widget=PasswordInput())

Step 2:

Create a basic HTML page and ensure that it is in your ‘templates’ directory. The HTML page will be called — my-login.html

From the code below, I have taken the liberty of adding a bootstrap theme from bootswatch. Feel free to edit your login form’s basic layout and structure, as you prefer.

We will fill these sections later on with the necessary code::

<!--- TO BE COMPLETED -->

my-login.html

<!-- my-login.html -->{% load static %}
<!DOCTYPE html>
<html lang="en">
<head> <title> Login </title> <meta charset="utf-8" /> <meta name="viewport" content="width-device-width, initial-scale=1, maximum-scale=1"/> <link rel="stylesheet" type="text/css" href="https://bootswatch.com/5/morph/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
</head>
<body> <br> <div class="container bg-white p-5" style="width:500px;"> <h4> Login to your account </h4> <br>
<br>
<form method="POST" autocomplete="off"> {% csrf_token %} <!--- TO BE COMPLETED --> <br> <br> <button type="submit" class="btn btn-secondary btn-lg w-100 btn-block p-4"> &nbsp; Login </button>
</form>

</div>
<br> </body></html>

Step 3:

Create a view that handles authentication for our Django project.

Ensure that you import the necessary functions as outlined below. As we can see, we need to import our LoginForm, which we created in our forms.py. We also need to import auth and authenticate to allow our users to be authenticated in order to log in.

# - views.pyfrom django.shortcuts import redirect, render
from django.http import HttpResponse
from .forms import LoginFormfrom django.contrib.auth.models import auth
from django.contrib.auth import authenticate

Next, we need to create our view itself.

We need to pass in our LoginForm() and prepare the form to post the username and password entered by the user.

After this, we can implement the authenticate function to check if the username and password entered by the user are matched in our database.

If the user exists and is not none we will allow the user to log in and return a basic HTTP response that confirms that they have logged in to their account — this proves that the authentication process was a success.

We need to also ensure that we render our form out to our HTML template — my-login.html

# - views.pydef my_login(request):    form = LoginForm()    if request.method == 'POST':        form = LoginForm(request, data=request.POST)        if form.is_valid():            username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None: auth.login(request, user) return HttpResponse("User has logged in!")
context = {'form':form} return render(request, 'my-login.html', context=context)

Step 4:

We can now return to our HTML page — my-login.html and render our form’s username and password inputs.

my-login.html

<!-- my-login.html -->{% load static %}
<!DOCTYPE html>
<html lang="en">
<head> <title> Login </title> <meta charset="utf-8" /> <meta name="viewport" content="width-device-width, initial-scale=1, maximum-scale=1"/> <link rel="stylesheet" type="text/css" href="https://bootswatch.com/5/morph/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
</head>
<body> <br> <div class="container bg-white p-5" style="width:500px;"> <h4> Login to your account </h4> <br>
<br>
<form method="POST" autocomplete="off"> {% csrf_token %} {{form.as_p}} <br> <br> <button type="submit" class="btn btn-secondary btn-lg w-100 btn-block p-4"> &nbsp; Login </button>
</form>

</div>
<br> </body></html>

Step 5:

Next, we need to connect and set our URLpath in urls.py.

We will need to pass in three parameters for our login URL path. First of all, we need to state our route, then attach our view and the name URL.

# - urls.pyfrom django.urls import pathfrom . import viewsurlpatterns = [    # - my-login url    path('my-login', views.my_login, name="my-login"),]

DONE — You have successfully implemented authentication within your Django project.

A final note…

For those that are interested in learning Django from scratch, feel free to check out my latest course:

Python Django: Ultimate Beginners Course — 2022

Originally published at https://www.cloudwithdjango.com on July 22, 2022.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arno Pretorius

Arno Pretorius

127 Followers

Hi, I’m Arno… I love cloud computing and django web development and I want to share my knowledge and experiences with you.