基于cookie和session的登录验证

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创建数据表。

posted @ 2018-02-23 21:44  xsan  阅读(1225)  评论(0编辑  收藏  举报