1.保存在用户浏览器
2.可以主动清除
3.可以被伪造
4.跨域名 Cookie 不共享
创建一个项目:user_manager 和应用: app01
创建数据库,添加 models.py
12345678910111213141516171819202122 | 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.pyfrom django.contrib import adminfrom django.urls import pathfrom app01 import viewsurlpatterns = [ path('admin/', admin.site.urls), path('login.html', views.login), path('index.html', views.index),] |
在 templates 文件夹下创建两个 html 文件
12345678910111213141516171819202122232425262728293031323334353637383940 | # 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
1234567891011121314151617181920212223242526 | from django.shortcuts import render, redirect# Create your views here.from app01 import modelsdef 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') |