基于session和cookie的登录验证(CBV模式)

基于session和cookie的登录验证(CBV模式)

urls.py

"""cookie_session URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from cookie import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login_CBV/',views.Login_CBV.as_view()),
    path('index_CBV/',views.Index_CBV.as_view()),
]

views.py

from django.shortcuts import render, redirect
from .models import User
from django import views


class Login_CBV(views.View):
    def get(self, request, *args, **kwargs):
        msg = ''
        return render(request, 'login.html', {'msg': msg})

    def post(self, request, *args, **kwargs):
        print(44444)
        name = request.POST.get("user")
        pwd = request.POST.get("pwd")
        c = User.objects.filter(user=name, pwd=pwd).count()
        if c:
            print(123123)
            request.session['is_log'] = 333
            request.session['username'] = name
            return redirect('/index_CBV/')
        else:
            msg = '用户名或密码有误'
            return render(request, 'login.html', {'msg': msg})


class Index_CBV(views.View):
    def get(self, request, *args, **kwargs):
        if request.session.get('is_log', None):
            user = request.session.get('username')
            return render(request, 'index.html', {'user': user})
        else:
            return redirect('/login_CBV/')

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_CBV/" 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>

 

posted @ 2018-02-24 22:11  xsan  阅读(204)  评论(0编辑  收藏  举报