基于cookie和session的登录验证

2018-06-18 01:27:10来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

一般不用修改settings.py,但是使用模版需要修改如下:(即将TEMPLATES中的DIRS改成[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 path
from cookie import views
urlpatterns = [
    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 = '用户名或密码有误'
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>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
欢迎 {{ user }}!
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<form action="/login/" method="post">
    {% csrf_token %}
    <div>
        <laber for="user">用户名</laber>
        <input id="user" type="text" name="user"/>
    </div>
    <div>
        <laber for="pwd">密码</laber>
        <input id="pwd" type="password" name="pwd">
    </div>
    <div>
        <input type="submit" value="登录">
    </div>
</form>
</body>
</html>

注意:由于我们将session存于数据库中所以要执行python manage.py makemigrations 后再执行python manage.py migrate创建数据表。

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python+Selenium笔记(十):元素等待机制

下一篇:Python垃圾回收机制