django框架本身自带有登录注册,也可以自己写登录注册,下面将介绍这这2种方式实登录注册
1.注册regist
注册采用的是form表单,提交到数据库,在登录的时候,查询数据看,看用户有没有注册,如果用户没有注册,则返回注册页面注册
(1)models.py文件里创建相关的字段: 用户名字/用户密码/cookies携带的ticket
from django.db import models
# Create your models here.
class Users(models.Model):
u_name = models.CharField(max_length=10)
u_password = models.CharField(max_length=255)
u_ticket = models.CharField(max_length=30, null=True)
class Meta:
db_table = 'day51_user'
django.db import models
# Create your models here.
class Users(models.Model):
u_name = models.CharField(max_length=10)
u_password = models.CharField(max_length=255)
u_ticket = models.CharField(max_length=30, null=True)
class Meta:
db_table = 'day51_user'
(2)urls.py 配置相关路由
from django.conf.urls import url
from uauth import views
urlpatterns = [
url(r'^regist/', views.regist),
url(r'^login/', views.login),
url(r'^logout', views.logout)
]
django.conf.urls import url
from uauth import views
urlpatterns = [
url(r'^regist/', views.regist),
url(r'^login/', views.login),
url(r'^logout', views.logout)
]
(3)views.py 书写regist方法
导入相关的包,在regist,login,logout都会使用到
import random
import time
from django.contrib import auth
from django.contrib.auth.hashers import make_password,check_password
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.core.urlresolvers import reverse
# Create your views here.
from uauth.models import Users
如果用户请求regist方法,则直接跳转到相关的html页面。
如果用户在html页面点击了post按钮,对密码进行加密后,将数据提交到数据库,并返回登录login页面。
获得post提交的表单文字,使用request.POST.get(' ')
def regist(request):
if request.method == 'GET':
return render(request, 'day6_regist.html')
if request.method == 'POST':
# 注册
name = request.POST.get('name')
password = request.POST.get('password')
# 对密码进行加密
password = make_password(password)
Users.objects.create(u_name=name, u_password=password)
return HttpResponseRedirect('/uauth/login/')
regist(request):
if request.method == 'GET':
return render(request, 'day6_regist.html')
if request.method == 'POST':
# 注册
name = request.POST.get('name')
password = request.POST.get('password')
# 对密码进行加密
password = make_password(password)
Users.objects.create(u_name=name, u_password=password)
return HttpResponseRedirect('/uauth/login/')
编写regist的提交表单, method方法选择'POST'
文件目录在templates下[图片上传中...(image.png-cc7763-1526105439415-0)]
{%csrf_token%}是针对提交的时候csrf跨域错误
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面title>
head>
<body>
<form action="" method="POST">
{% csrf_token %}
注册姓名:<input type="text" name="name">
注册密码:<input type="password" name="password">
<input type="submit" value="提交">
form>
body>
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面title>
head>
<body>
<form action="" method="POST">
{% csrf_token %}
注册姓名:<input type="text" name="name">
注册密码:<input type="password" name="password">
<input type="submit" value="提交">
form>
body>
html>
2.登录login
(1)配置路由urls.py, 与注册的时候一样的操作
(2)配置views.py, 编写login方法
如果是GET请求,则跳转到登录的html界面中
def login(request):
if request.method == 'GET':
return render(request, 'day6_login.html')
login(request):
if request.method == 'GET':
return render(request, 'day6_login.html')
如果是POST请求,则将获得的用户密码与数据库的用户密码进行比较。如果相同,就赋值一个ticker到浏览器上,将ticket存入数据库中,这样后续的浏览器操作只需判断ticket是否正确就好,如果错误,返回登录界面
知识点
绑定cookie命令: set_cookie
查询一个用户是否存在:exists()
def login(request):
if request.method == 'GET':
return render(request, 'day6_login.html')
if request.method == 'POST':
# 如果登录成功,绑定参数到cookie中,set_cookie
name = request.POST.get('name')
password = request.POST.get('password')
# 查询用户是否在数据库中
if Users.objects.filter(u_name=name).exists():
user = Users.objects.get(u_name=name)
if check_password(password, user.u_password):
# ticket = 'agdoajbfjad'
ticket = ''
for i in range(15):
s = 'abcdefghijklmnopqrstuvwxyz'
# 获取随机的字符串
ticket += random.choice(s)
now_time = int(time.time())
ticket = 'TK' + ticket + str(now_time)
# 绑定令牌到cookie里面
# response = HttpResponse()
response = HttpResponseRedirect('/stu/index/')
#max_age 存活时间(秒)
response.set_cookie('ticket', ticket, max_age=10000)
# 存在服务端
user.u_ticket = ticket
user.save() #保存
return response
else:
# return HttpResponse('用户密码错误')
return render(request, 'day6_login.html', {'password': '用户密码错误'})
else:
# return HttpResponse('用户不存在')
return render(request, 'day6_login.html', {'name': '用户不存在'})
login(request):
if request.method == 'GET':
return render(request, 'day6_login.html')
if request.method == 'POST':
# 如果登录成功,绑定参数到cookie中,set_cookie
name = request.POST.get('name')
password = request.POST.get('password')
# 查询用户是否在数据库中
if Users.objects.filter(u_name=name).exists():
user = Users.objects.get(u_name=name)
if check_password(password, user.u_password):
# ticket = 'agdoajbfjad'
ticket = ''
for i in range(15):
s = 'abcdefghijklmnopqrstuvwxyz'
# 获取随机的字符串
ticket += random.choice(s)
now_time = int(time.time())
ticket = 'TK' + ticket + str(now_time)
# 绑定令牌到cookie里面
# response = HttpResponse()
response = HttpResponseRedirect('/stu/index/')
#max_age 存活时间(秒)
response.set_cookie('ticket', ticket, max_age=10000)
# 存在服务端
user.u_ticket = ticket
user.save() #保存
return response
else:
# return HttpResponse('用户密码错误')
return render(request, 'day6_login.html', {'password': '用户密码错误'})
else:
# return HttpResponse('用户不存在')
return render(request, 'day6_login.html', {'name': '用户不存在'})
登录相关的html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面title>
head>
<body>
<form action="" method="POST">
{% csrf_token %}
登录姓名:<input type="text" name="name">
登录密码:<input type="password" name="password">
<input type="submit" value="提交">
form>
body>
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面title>
head>
<body>
<form action="" method="POST">
{% csrf_token %}
登录姓名:<input type="text" name="name">
登录密码:<input type="password" name="password">
<input type="submit" value="提交">
form>
body>
html>
相关的数据库
image.png
补充说明:如何在主页中判断ticket
知识点:获得浏览器cookie携带的ticket: request.COOKIES.get('ticket')
这只能判断一个网页需不需要进行判断验证,如果需要很多网页进行验证,这是需要采用中间件,这个稍候会涉及到
def index(request):
if request.method == 'GET':
# 获取所有学生信息
ticket = request.COOKIES.get('ticket')
if not ticket:
return HttpResponseRedirect('/uauth/login/')
if Users.objects.filter(u_ticket=ticket).exists():
stuinfos = StudentInfo.objects.all()
return render(request, 'index.html', {'stuinfos': stuinfos})
else:
return HttpResponseRedirect('/uauth/login/')
index(request):
if request.method == 'GET':
# 获取所有学生信息
ticket = request.COOKIES.get('ticket')
if not ticket:
return HttpResponseRedirect('/uauth/login/')
if Users.objects.filter(u_ticket=ticket).exists():
stuinfos = StudentInfo.objects.all()
return render(request, 'index.html', {'stuinfos': stuinfos})
else:
return HttpResponseRedirect('/uauth/login/')
3.登出系统
实现登出目的,选择删除数据库中的ticket:delete_cookie
登出过后,自动跳转到登录界面
def logout(request):
if request.method == 'GET':
# response = HttpResponse()
response = HttpResponseRedirect('/uauth/login/')
response.delete_cookie('ticket')
return response
logout(request):
if request.method == 'GET':
# response = HttpResponse()
response = HttpResponseRedirect('/uauth/login/')
response.delete_cookie('ticket')
return response
4.中间件middleware
应用:在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。
process_request(self,request) :当用户发起请求的时候会依次经过所有的的中间件,这个时候的请求是process_request :
process_view(self, request, callback, callback_args, callback_kwargs) :进入views函数, 执行process_view
process_template_response(self,request,response) : 只有当views函数中返回的对象中具有render方法,是就会直接process_template_responseprocess
process_exception(self, request, exception) : 当views的函数中出现错误时,就会执行process_exception方法
process_response(self, request, response)
:views函数处理后,在依次穿过中间件,这个时候是process_response,最后返回给请求者
5. 使用中间件完成登录的验证
中间件return None 或什么都不返回的时候表示什么都不做,跳过这一个过程
配置中间件,实现登录的验证
(1)配置settings.py
1) 在主工程文件下创建一个utils文件,
在utils里: a. 创建中间件文件(名字自己取) b.创建一个工程文件 __init__.py
image.png
2)settings.py配置
在MIDDILEWARE里添加相关的文件路径
QQ图片20180512150130.png
3) 配置相关的中间件文件
from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
from uauth.models import Users
from stu.models import Countaddstu
class AuthMiddleware(MiddlewareMixin):
def process_request(self, request):
# 统一验证登录
# return none 或者 不写return才会继续往下执行, 不需要执行
if request.path == '/uauth/login/' or request.path == '/uauth/regist/':
return None
ticket = request.COOKIES.get('ticket')
if not ticket:
return HttpResponseRedirect('/uauth/login/')
users = Users.objects.filter(u_ticket=ticket)
if not users:
return HttpResponseRedirect('/uauth/login/')
# 将user赋值在request请求的user上,以后可以直接判断user有没有存在
# 备注,django自带的有user值
request.user = users[0]
django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
from uauth.models import Users
from stu.models import Countaddstu
class AuthMiddleware(MiddlewareMixin):
def process_request(self, request):
# 统一验证登录
# return none 或者 不写return才会继续往下执行, 不需要执行
if request.path == '/uauth/login/' or request.path == '/uauth/regist/':
return None
ticket = request.COOKIES.get('ticket')
if not ticket:
return HttpResponseRedirect('/uauth/login/')
users = Users.objects.filter(u_ticket=ticket)
if not users:
return HttpResponseRedirect('/uauth/login/')
# 将user赋值在request请求的user上,以后可以直接判断user有没有存在
# 备注,django自带的有user值
request.user = users[0]
6. 至此,自己建造的登录验证系统已经完成
更多Python视频、源码、资料加群683380553免费获取
自带的登录验证系统中不需要自己手动的设置ticket
1.settings.py文件中配置没登录的跳转页面
LOGIN_URL = '/uauth/dglogin'
= '/uauth/dglogin'
2.urls.py中配置相关路由
from django.conf.urls import url
from uauth import views
urlpatterns = [
url(r'dglogin/', views.dglogin),
url(r'^dgregist/', views.dgregist),
url(r'^dglogout/', views.dglogout)
]
django.conf.urls import url
from uauth import views
urlpatterns = [
url(r'dglogin/', views.dglogin),
url(r'^dgregist/', views.dgregist),
url(r'^dglogout/', views.dglogout)
]
3. views.py导入相关的库文件
from django.contrib import auth
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
django.contrib import auth
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
4.views.py文件中书写注册dgregist方法
from django.contrib.auth.models import User
def dgregist(request):
if request.method == 'GET':
return render(request, 'day6_regist.html')
if request.method == 'POST':
name = request.POST.get('name')
password = request.POST.get('password')
User.objects.create_user(username=name, password=password)
return HttpResponseRedirect('/uauth/dglogin/')
django.contrib.auth.models import User
def dgregist(request):
if request.method == 'GET':
return render(request, 'day6_regist.html')
if request.method == 'POST':
name = request.POST.get('name')
password = request.POST.get('password')
User.objects.create_user(username=name, password=password)
return HttpResponseRedirect('/uauth/dglogin/')
5. views.py文件中书写注册dglogin方法
def dglogin(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == 'POST':
name = request.POST.get('name')
password = request.POST.get('password')
# 验证用户名和密码,通过的话,返回User对象
user = auth.authenticate(username=name, password=password)
if user:
auth.login(request, user)
return HttpResponseRedirect('/stu/index/')
else:
return render(request, 'index.html')
dglogin(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == 'POST':
name = request.POST.get('name')
password = request.POST.get('password')
# 验证用户名和密码,通过的话,返回User对象
user = auth.authenticate(username=name, password=password)
if user:
auth.login(request, user)
return HttpResponseRedirect('/stu/index/')
else:
return render(request, 'index.html')
6. 在app的urls.py中设置验证require
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from stu import views
urlpatterns = [
url(r'addstu/', login_required(views.addStu), name='add'),
url(r'index/', login_required(views.index)),
]
django.conf.urls import url
from django.contrib.auth.decorators import login_required
from stu import views
urlpatterns = [
url(r'addstu/', login_required(views.addStu), name='add'),
url(r'index/', login_required(views.index)),
]
7.登出dglogout
def dglogout(request):
if request.method == 'GET':
auth.logout(request)
dglogout(request):
if request.method == 'GET':
auth.logout(request)
return HttpResponseRedirect('/uauth/dglogin')