Good Place. Good Things. Good Time.

Authentication in Django

Authentication in Django

Introduction to Authentication in Django

As far as Django is concerned the Django system comes with a built-in authentication system. This built-in authentication system is a user-level authentication system. This user-level authentication system represents user objects. These user objects can be used across the Django framework for various authentication-based 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 involved processes like access to view an object, the addition of an object and setting permission in the object level, etc.



How Authentication works in Django?

From Django’s perspective, authentication is achieved by means of the above-mentioned setting 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. As like the authentication method is used checking the authentication in a quick manner against the database. So processes like these are involved for setting the authentication setup in Django based systems. It may also involve processes like access to view an object, the addition of an object and setting permission in the object level, etc. As mentioned before from a Django perspective the authentication is achieved by means of the above-mentioned setting values and more specifically the authentication is achieved corresponding to the user objects mentioned in these authentication items.

Create a Django Authentication setup

1. Changes in file: The Authentication charge at the same time as submitted to be stored and at the same time as retrieved ought to be pulled from the database. This can be completed via the object created for the model. The way of doing this is described withinside the beneath neath given section.


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):

2. Changes in file: The below-given file mentions the changes in the settings file for Authentication.


from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
Template_DIR = os.path.join(BASE_DIR,'Templates/Mainpage')
DEBUG = True
# Application definition
ROOT_URLCONF = 'Matrimony.urls'
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'context_processors': [
WSGI_APPLICATION = 'Matrimony.wsgi.application'
# Database
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
# Password validation
'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
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
#STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

3. Changes in file: The Media root and document root variable need to be instantiated inside the file as below. The changes for the file are mentioned below.

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"signup/", views.Sign_up_request, name="register"),
url(r"login/", views.login_request, name="login"),
]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

4.  Create a view for the form:  The view for


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 =
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(" 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)
if form.is_valid():
user =
login(request, user)
messages.success(request, "Registration successful." )
return redirect("")
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), f"You are now logged in as {username}.")
return redirect("")
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:
print('2',request.user.is_authenticated, request.user), "Logged out successfully!")
return redirect("")


Authentication in Django output 1

Authentication in Django output 2


The above-given article mentions the way to claim how the Authentication area works, the syntax of the identical is mentioned in conjunction with the procedure of ways the Authentication relationships work in Django. The example clearly explains setting up the login, logout, and sign-up processes in relation to Django. These processes are explained with the output snaps of the executions.

Recommended Articles

This is a guide to Authentication in Django. Here we discuss the way to claim how the Authentication area works in Django. You may also have a look at the following articles to learn more –

  1. Django GROUP BY
  2. Django Session
  3. Django Response
  4. Django Forms

The post Authentication in Django appeared first on EDUCBA.

Read original article here: Authentication in Django

Read original article here: Authentication in Django

Disclaimers and Denial of responsibility..!

Denial of responsibility! is an automatic aggregator of all media around the world. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – . The content will be deleted within 72 hours.
You might also like
Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.