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 %}{% endblock %}Login
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. p>
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.