User authentication is a crucial aspect for any web application that wants to protect certain resources and allow access only to authorized users. In Django, authenticating users is facilitated by its built-in authentication library. In this section, we'll explore how to create a Django project that includes user authentication.

To get started, we first need to install Django. This can be done using pip, the Python package installer. In the terminal, just run the command 'pip install django'. Once installed, we can create a new Django project by running 'django-admin startproject myproject'.

Once the project is created, we need to create a new application to handle user authentication. This can be done by running 'python manage.py startapp authentication' in the root of the project. This will create a new folder called 'authentication' with several files that will be used to configure the authentication enforcement.

Next, we need to add the new app to the list of INSTALLED_APPS in settings.py. This will allow Django to recognize the authentication application and include its functionality in the project. The INSTALLED_APPS list should now include 'authentication'.

Next, we need to configure user authentication. Django comes with a built-in authentication system that we can use. For that, we need to add the following line to the settings.py file: 'AUTH_USER_MODEL = 'authentication.User'.

This tells Django to use the user model defined in the authentication application for all authentication operations. Now we need to create this user model. In models.py in the authentication application, add the following code:

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

This creates a user model that inherits from AbstractUser, a base user model that includes fields like username, password, email, first_name, last_name, etc. We can add additional fields if needed, but for this example, let's keep things simple.

Now, we need to create the views to handle login and logout. In views.py in the authentication application, add the following code:

from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse
from django.shortcuts import render, redirect

def login_view(request):
    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('home')
        else:
            return HttpResponse('Invalid credentials')
    else:
        return render(request, 'authentication/login.html')

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

These views handle login and logout respectively. The login view checks if the request method is POST. If so, it tries to authenticate the user with the supplied username and password. If authentication is successful, the user is logged in and redirected to the home page. If authentication fails, an HTTP response with the message 'Invalid credentials' is returned. If the request method is not POST, the login page is rendered.

The logout view simply logs the user out and redirects to the login page.

Now, we need to create the login templates. Create a new folder called 'templates' in the authentication application folder and inside that create a new folder called 'authentication'. Inside this folder, create a new file called 'login.html' and add the following code:

{% extends 'base_generic.html' %}

{% block content %}
  

Login

{% csrf_token %} Username:
Password:
{% endblock %}

This is a simple login template that extends the base_generic.html template and replaces the content block with a login form.

Finally, we need to add the URLs for the login and logout views. In urls.py in the authentication application, add the following code:

from django.urls import path
from . import views

urlpatterns = [
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
]

This adds the URLs for the login and logout views, respectively. Now, if we run the Django development server with 'python manage.py runserver' and navigate to 'http://localhost:8000/login', we should see the login page and be able to login with an existing user.

In short, user authenticationos is an important part of any web application, and Django makes it easy to implement this functionality. With Django's built-in authentication system, we can easily secure resources and allow access only to authorized users.

Now answer the exercise about the content:

What is the process for configuring user authentication in a Django project?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Creating a Django Project: Authorization and Permissions

Next page of the Free Ebook:

68Creating a Django Project: Authorization and Permissions

3 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text