Updated May 20, 2023
Introduction to Authentication in Django
As far as Django is concerned, the Django system has a built-in authentication system. This built-in authentication system is a user-level authentication system. This user-level authentication system represents user objects. Developers can leverage the user objects extensively across the Django framework to address diverse authentication-related needs. This is among the key advantages of authentication systems. From an admin level, the authentication process involves creating users, creating super users, changing passwords, authenticating the users, and related jobs. It may also include processes like access to view an object, adding an object and setting permission in the object level, etc.
Syntax:
'django.contrib.auth'
'django.contrib.auth.middleware.AuthenticationMiddleware'
How does Authentication work in Django?
From Django’s perspective, authentication is achieved using the setting mentioned above values. These two values are made by default to a project created in Django. From an admin level, the authentication process involves creating users, creating super users, changing passwords, authenticating the users, and related jobs. Django plays a significant role in the process of setting the authentications and checking the authentications flexibly. The authentication method is used to check the authentication quickly against the database. Such processes are involved in setting the authentication setup in Django-based systems. It may also include processes like access to view an object, adding an object and setting permission in the object level, etc. From a Django perspective, developers accomplish authentication by utilizing the values specified in the relevant settings. Specifically, the authentication process revolves around the user objects associated with these authentication components.
Create a Django Authentication setup
1. Changes in Models.py file
To store the submitted Authentication charge and retrieve it from the database, you can use the object created for the model. The process is explained in the following section of the views.py file:
models.py
from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Bride(models.Model):
Authentication_Examplename = models.CharField(max_length=200,null=True)
Authentication_Examplethegai = models.CharField(max_length=200,null=True)
Authentication_ExampleState = models.CharField(max_length=50,null=True)
Authentication_ExampleDistrict = models.CharField(max_length=50,null=True)
Authentication_ExampleAddress = models.TextField(null=True)
Authentication_ExamplePhone = models.BigAuthentication_ExampleField(null=True)
Authentication_Exampleprofession = models.CharField(max_length=200,null=True)
Authentication_Examplesalary = models.BigAuthentication_ExampleField(null=True)
Authentication_ExampleUnder_Graduation_Degree = models.CharField(max_length=200,null=True)
Authentication_ExampleUnder_Graduation_college = models.CharField(max_length=400,null=True)
Authentication_ExamplePost_Graduation_Degree = models.CharField(max_length=200,null=True)
Authentication_ExamplePost_Graduation_college = models.CharField(max_length=400,null=True)
Authentication_ExampleRasi = models.CharField(max_length=200,null=True)
Authentication_ExampleNakshatra = models.CharField(max_length=200,null=True)
Authentication_ExampleCreator = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def _str_(self):
return self.name
2. Changes in Settings.py file
The below-given file mentions the changes in the settings file for Authentication.
Settings.py:
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
Template_DIR = os.path.join(BASE_DIR,'Templates/Mainpage')
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'matrimony_pages',]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',]
ROOT_URLCONF = 'Matrimony.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'Matrimony.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
#STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
#print(STATICFILES_DIRS)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
#print(STATIC_ROOT)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
3. Changes in url.py file
The Media root and document root variables must be instantiated inside the url.py file below. The changes for the url.py file are mentioned below.
url.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from matrimony_pages import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$',views.Welcome_page,name='Welcome_page'),
url(r'Mainpage/',views.Main_page,name='Main_page'),
url(r'form/',views.form_view,name='form_view'),
url(r"signup/", views.Sign_up_request, name="register"),
url(r"login/", views.login_request, name="login"),
path(r'profile//',views.Authentication_Examplepage,name='profile'),
url(r'logout/',views.logout_request,name='logout'),
url(r'reg/',views.Authentication_Example,reg_user,name='reg'),
path(r'update//',views.form_update,name='update'),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4. Create a view for the form
views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import NewUserForm,Valueform
from django.contrib.auth import login,authenticate,logout
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test,login_required
from django.core.paginator import Paginator
from django.http import Authentication
def All_users(request):
User_entries = User.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(User_entries, 5)
users = paginator.page(page)
print(" Has other pages : ",users.has_other_pages())
print(" Has next page : ",users.has_next())
print(" Has previous page : ",users.has_previous())
print(" Has previous page : ",users.has_previous())
print(" Start Index : ",users.start_index())
print(" End Index : ",users.end_index())
if users.has_next():
print(" Next page Number: ",users.next_page_number())
elif users.has_previous():
print(" Has Previous page Number: ",users.previous_page_number())
print(paginator,users)
print(" Has other pages : ",users.has_other_pages())
print(" Has next page : ",users.has_next())
print(" Has previous page : ",users.has_previous())
print(" Has previous page : ",users.has_previous())
print(" Start Index : ",users.start_index())
print(" End Index : ",users.end_index())
return render(request,"All_users.html",{'users':users})
def Sign_up_request(request):
if request.method == "POST":
form = NewUserForm(request.POST)
print(form.is_valid())
if form.is_valid():
user = form.save()
login(request, user)
print(User.objects.all())
messages.success(request, "Registration successful." )
return redirect("http://127.0.0.1:8000/")
messages.error(request, "Unsuccessful registration. Invalid information.")
form = NewUserForm
return render (request,template_name="Signup.html", context={"Sign_up_form":form})
def login_request(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:
print('1',request.user.is_authenticated, request.user)
login(request, user)
# logout(request)
print('1',request.user.is_authenticated, request.user)
messages.info(request, f"You are now logged in as {username}.")
return redirect("http://127.0.0.1:8000/")
else:
messages.error(request,"Invalid username or password.")
form = AuthenticationForm()
return render(request=request, template_name="login.html", context={"login_form":form})
def logout_request(request):
if request.user.is_authenticated:
logout(request)
print('2',request.user.is_authenticated, request.user)
messages.info(request, "Logged out successfully!")
return redirect("http://127.0.0.1:8000/")
Output:
Conclusion
The above article explains the functioning of the Authentication area in Django. It provides the syntax for the relevant methods and describes how the Authentication relationships work. Additionally, it includes a comprehensive example that illustrates the setup of login, logout, and sign-up processes in Django. The example consists of screenshots of the output, showcasing the execution of these processes.
Recommended Articles
We hope that this EDUCBA information on “Authentication in Django” was beneficial to you. You can view EDUCBA’s recommended articles for more information.