Cookie-based and session-based logon verification and cookiesession Verification

Source: Internet
Author: User

Cookie-based and session-based logon verification and cookiesession Verification

Settings. py

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',]

Generally, you do not need to modify settings. py, but you need to modify the template as follows: (Change DIRS in TEMPLATES to [OS. path. join (BASE_DIR, 'templates')])

TEMPLATES = [    {        'BACKEND': 'django.template.backends.django.DjangoTemplates',        'DIRS':  [os.path.join(BASE_DIR, 'templates')],        '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',            ],        },    },]

 

Urls. py

from django.urls import pathfrom cookie import viewsurlpatterns = [    path('admin/', admin.site.urls),    path('login/',views.login),    path('index/',views.index),]

Models. py

from django.db import models# Create your models here.class User(models.Model):    user=models.CharField(max_length=20,unique=True,db_index=True)    pwd=models.CharField(max_length=20,db_index=True)    def __str__(self):        return self.user

Views. py

From django. shortcuts import render, redirect
From. models import User


# Create your views here.
Def login (request ):
Msg =''
If request. method = 'post ':
Name = request. POST. get ("user ")
Pwd = request. POST. get ("pwd ")
C = User. objects. filter (user = name, pwd = pwd). count ()
If c:
Request. session ['is _ log'] = 111
Request. session ['username'] = name
Return redirect ('/index /')
Else:
Msg = 'incorrect user name or password'
Return render (request, 'login.html ', {'msg': msg })
Else:
Return render (request, 'login.html ', {'msg': msg })


Def index (request ):
Print (request. session. get ('is _ log '))
If request. session. get ('is _ log', None ):
User = request. session. get ('username ')
Return render (request, 'index.html ', {'user': user })
Else:
Return redirect ('/login /')


Def bb (request ):
Return redirect ('/login /')

Index.html

<! DOCTYPE html> 

Login.html

<! DOCTYPE html> 

Note: Because we store sessions in the database, we need to execute python manage. py makemigrations and then execute python manage. py migrate to create a data table.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.