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.

Syntax:

'django.contrib.auth'
'django.contrib.auth.middleware.AuthenticationMiddleware'

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 Models.py 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 views.py section.

(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 variable need to be instantiated inside the url.py file as 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:  The view for

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

Authentication in Django output 1

Authentication in Django output 2

Conclusion

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! TheTopMag.com 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 – jamesonline999@gmail.com . 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.