Cookie:
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# index.htmlTitle
添加 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
输入错误的用户名或密码
输入正确的用户名和密码
总结
以上所述是小编给大家介绍的基于Django 使用 cookie 实现简单的用户管理功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!