1.数据库结构模型model.pyfrom django.db import models
import random
import string
def random_string(length=10):
letters = string.ascii_letters + string.digits
return ''.join(random.choice(letters) for i in range(length))
# 创造随机数作为生成新用户得默认值密码 因为 不让为空
class user(models.Model):
name = models.CharField(max_length=10,unique=True)
password = models.CharField(max_length=50,default=random_string)
age = models.IntegerField(default=18)
class Meta:
db_table = 'tb_user'
2.项目结构树
--document.html
--index.html
--login.html
--register.html
3.注册页面得源码<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
</head>
<body>
<h1>我要注册</h1>
<hr>
<a href="{% url 'uapp:index' %}">返回首页</a>
<form action="" method="post">
{% csrf_token %}
<p>用户名:<input type="text" name="uname"></p>
<p>密码:<input type="password" name="upassword"></p>
<p>年龄:<input type="text" name="uage"></p>
<p><button>注册</button></p>
</form>
</body>
</html>
关于注册表单提交拦截跨域拦截有两个解决方案
a.直接干掉django主目录setting文件里面的关于跨域验证得中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
但是这样并不安全
b.再html提交表单中设置token头这个只是模板语法里面的方案,前后端混合开发,具体到前端写法另外得一个样子
3.防止反复登录需要书写cookie相当于给用户发一个身份证 不用每次都去输入密码才进入登录状态view.py的完整源码
其次换账号呢就写注销cookie得东西
import datetime
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect, reverse
from django.shortcuts import render
from app.models import *
# Create your views here.
# 请求
def test(request):
# print(request) # <WSGIRequest: GET '/app/test/'> 请求对象
print(request.method) # 请求方式GET
print(request.GET) # GET参数<QueryDict: {}>
print(request.GET.get('name')) # GET参数获取域名得汇总name得参数
print(request.GET.getlist('name')) # 获取域名里面的名字列表参数
print(request.POST) # POST参数<QueryDict: {}>
print(request.path) # path路径参数/app/test/
print(request.get_full_path) # 打印完整路径
print(
request.COOKIES) # 会话技术{'csrftoken': 'JjuvXMJv1aQ41wcLn1rqnXi3hqAZO7Rs', 'sessionid': 'izlsvufx848ucpqk0a5gg636a3vlsqno'}
print(request.session) # <django.contrib.sessions.backends.db.SessionStore object at 0x0000018E6461EE50>
print(request.FILES) # 上传文件
print(request.META['REMOTE_ADDR']) # 客户端ip地址
return HttpResponse("测试返回")
# 相应
def myResponse(request):
pass
# 1.返回字符串 使用很少
# return HttpResponse('哈')
# 2.返回模板,前后端你不分离
# return render(request,'index.html')
# 3.重定向
# return redirect('/app/test/')
# 4.返回json文件 ,前后端分离方式
return JsonResponse({'data': 'hello'})
def index(request):
# cookie
userName = request.COOKIES.get('userName')
uName = user.objects.filter(name=userName).first()
print(userName,uName)
return render(request, 'index.html', {'userName': uName})
def dom(request):
return render(request, 'document.html')
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
elif request.method == 'POST':
uname = request.POST.get('uname')
upassword = request.POST.get('upassword')
print(uname, upassword)
# 登录验证
users = user.objects.filter(name=uname, password=upassword)
# print(users)
if users.exists():
# 获取当前用户对象
userM = users.first()
# 设置cookie
response = redirect(reverse('uapp:document'))
# max_age cookie过期时间设置三种方案
# response.set_cookie('userid', user.name, max_age=3600)
# response.set_cookie('userid', user.name, expires=datetime.datetime(2024, 3, 6, 4, 5))
response.set_cookie('userName', users.first().name, expires=datetime.datetime.now() + datetime.timedelta(days=7))
return response
else:
return HttpResponse('登录失败')
def register(request):
# 通过判断请方式返回数据
if request.method == 'GET':
return render(request, 'register.html')
elif request.method == 'POST':
# 接受前端能表单提交过来得数据
uname = request.POST.get('uname')
upassword = request.POST.get('upassword')
uage = request.POST.get('uage')
print(uname, upassword, uage)
# 往数据库填充数据库
users = user.objects.filter(name=uname)
if users.exists(): # 遍历判断结果是否与数据库里面的内容想通
return HttpResponse('用户名重复不能注册了')
try:
users = user(name=uname, password=upassword, age=uage)
users.save()
except Exception as e:
return HttpResponse('注册失败了')
return redirect(reverse('uapp:login'))
def logout(request):
response = redirect(reverse('uapp:index'))
response.delete_cookie('userName')
return response
4.session得写法方案 view.py
import datetime
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect, reverse
from django.shortcuts import render
from app.models import *
# Create your views here.
# 请求
def test(request):
# print(request) # <WSGIRequest: GET '/app/test/'> 请求对象
print(request.method) # 请求方式GET
print(request.GET) # GET参数<QueryDict: {}>
print(request.GET.get('name')) # GET参数获取域名得汇总name得参数
print(request.GET.getlist('name')) # 获取域名里面的名字列表参数
print(request.POST) # POST参数<QueryDict: {}>
print(request.path) # path路径参数/app/test/
print(request.get_full_path) # 打印完整路径
print(
request.COOKIES) # 会话技术{'csrftoken': 'JjuvXMJv1aQ41wcLn1rqnXi3hqAZO7Rs', 'sessionid': 'izlsvufx848ucpqk0a5gg636a3vlsqno'}
print(request.session) # <django.contrib.sessions.backends.db.SessionStore object at 0x0000018E6461EE50>
print(request.FILES) # 上传文件
print(request.META['REMOTE_ADDR']) # 客户端ip地址
return HttpResponse("测试返回")
# 相应
def myResponse(request):
pass
# 1.返回字符串 使用很少
# return HttpResponse('哈')
# 2.返回模板,前后端你不分离
# return render(request,'index.html')
# 3.重定向
# return redirect('/app/test/')
# 4.返回json文件 ,前后端分离方式
return JsonResponse({'data': 'hello'})
def index(request):
# cookie
# userName = request.COOKIES.get('userName')
# session获取方案
userName = request.session.get('userName','admin')
uName = user.objects.filter(name=userName).first()
print(userName,uName)
return render(request, 'index.html', {'userName': uName})
def dom(request):
return render(request, 'document.html')
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
elif request.method == 'POST':
uname = request.POST.get('uname')
upassword = request.POST.get('upassword')
print(uname, upassword)
# 登录验证
users = user.objects.filter(name=uname, password=upassword)
# print(users)
if users.exists():
# 获取当前用户对象
userM = users.first()
# 设置cookie
response = redirect(reverse('uapp:document'))
# max_age cookie过期时间设置三种方案
# response.set_cookie('userid', user.name, max_age=3600)
# response.set_cookie('userid', user.name, expires=datetime.datetime(2024, 3, 6, 4, 5))
# response.set_cookie('userName', users.first().name, expires=datetime.datetime.now() + datetime.timedelta(days=7))
# 使用session
request.session['userName'] = uname
request.session.set_expiry(3600*2)
return response
else:
return HttpResponse('登录失败')
def register(request):
# 通过判断请方式返回数据
if request.method == 'GET':
return render(request, 'register.html')
elif request.method == 'POST':
# 接受前端能表单提交过来得数据
uname = request.POST.get('uname')
upassword = request.POST.get('upassword')
uage = request.POST.get('uage')
print(uname, upassword, uage)
# 往数据库填充数据库
users = user.objects.filter(name=uname)
if users.exists(): # 遍历判断结果是否与数据库里面的内容想通
return HttpResponse('用户名重复不能注册了')
try:
users = user(name=uname, password=upassword, age=uage)
users.save()
except Exception as e:
return HttpResponse('注册失败了')
return redirect(reverse('uapp:login'))
def logout(request):
response = redirect(reverse('uapp:index'))
# response.delete_cookie('userName')
session_id = request.session.session_key
request.session.delete(session_id)
return response
|