Django 使用 cookie 实现简单的用户管理功能
人气:0Cookie:
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
输入错误的用户名或密码
输入正确的用户名和密码
总结
以上所述是小编给大家介绍的基于Django 使用 cookie 实现简单的用户管理功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
您可能感兴趣的文章:
加载全部内容