Django 使用 cookie 实现简单的用户管理

Python publisher01 40℃

1.保存在用户浏览器
2.可以主动清除
3.可以被伪造
4.跨域名 Cookie 不共享


创建一个项目:user_manager 和应用: app01

创建数据库,添加 models.py

from django.db import models
# Create your models here.
class Classes(models.Model):
    caption = models.CharField(max_length=32)
class Student(models.Model):
    name = models.CharField(max_length=32)
    cls = models.ForeignKey(Classes, on_delete=models.CASCADE)
class Teacher(models.Model):
    name = models.CharField(max_length=32)
    cls = models.ForeignKey(Classes, on_delete=models.CASCADE)
class Administrator(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)

修改 urls.py

from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login.html', views.login),
    path('index.html', views.index),
]

在 templates 文件夹下创建两个 html 文件

# login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="login.html" method="post">
    {% csrf_token %}
    <div>
        <label for="user">用户名: </label>
        <input id="user" type="text" name="user">
    </div>
    <div>
        <label for="pwd">密码: </label>
        <input id="pwd" type="password" name="pwd">
    </div>
    <div>
        <label></label>
        <input type="submit" value="登录">
        <span style="color: red;">{{ msg }}</span>
    </div>
</form>
</body>
</html>
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1> Hello {{ username }} </h1>
</body>
</html>

添加 views.py

from django.shortcuts import render, redirect
# Create your views here.
from app01 import models
def login(req):
    # models.Administrator.objects.create(
    #     username='klvchen',
    #     password='klvchen'
    # )
    message = ""
    if req.method == "POST":
        user = req.POST.get('user')
        pwd = req.POST.get('pwd')
        c = models.Administrator.objects.filter(username=user, password=pwd).count()
        if c:
            rep = redirect('index.html')
            rep.set_cookie('username', user)
            return rep
        else:
            message = "用户名或密码错误"
    return render(req, 'login.html', {'msg': message})
def index(req):
    username = req.COOKIES.get('username')
    if username:
        return render(req, 'index.html', {'username': username})
    else:
        return redirect('/login.html')

初始化数据库

python manage.py makemigrations
python manage.py migrate

启动

python manage.py runserver 8000

访问 http://127.0.0.1:8000/index.html

输入错误的用户名或密码

输入正确的用户名和密码

转载请注明:Python量化投资 » Django 使用 cookie 实现简单的用户管理

喜欢 (0)or分享 (0)