Django重新整理2
Auth认证:
1.分配路由和创建视图函数
2.在视图函数中引用Django为我们提供的用户认证组建Auth
3.直接进行判断:
def login(request): if request.method =='GET': return render(request,'login.html') else: user = request.POST.get('user') pwd= request.POST.get('pwd') auth_obj=auth.authenticate(username=user,password=pwd) if auth_obj: #保存用户信息 auth.login(request,user_obj) return redirect("/index/") else: return redirect("/login/") #login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <input type="text" name="uer"> <input type="password" name="pwd"> <input type="submit"> </form> </body> </html> #index.html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> 当前用户:{{ name }} 当前用户:{{ request.user.username }} <a href="/logout/">注销</a> <a href="/set_password/">修改密码</a> </body> </html>
session的设置
1.分配路由和创建视图函数
2.
Django默认支持Session,并且默认是将Session数据存储在数据库中,即:django_session 表中。 def login_session(request): if request.method=='GET': return render(request,'login.html') else: user=request.POST.get('uer') pwd=request.POST.get('pwd') print(user,pwd) user_obj=UserInfo.objects.filter(user=user,pwd=pwd).first() if user_obj: # 用户认证信息存储 request.session["susername"]=user request.session["slogin"]=True ''' if request.COOKIE.get("sessionid"): random_str=request.COOKIE.get("sessionid") 在django-seesion表中过滤session-key=random_str的记录进行update else: 1 生成一个随机字符串 23423hkjsf890234sd 2 向django-session表中插入记录 session-key session-data 23423hkjsf890234sd {"susername":"egon","slogin":True} 3 响应set_cookie : {"sessionid":23423hkjsf890234sd} ''' return redirect("/index_session/") else: return HttpResponse('error') #取session def index_session(request): ''' request.session 1 request.COOKIE.get("sessionid") :23423hkjsf890234sd 2 在django-session表过滤session-key=23423hkjsf890234sd的记录 3 取过滤记录的session-data反序列化成数据字典:{"susername":"egon","slogin":True} ''' slogin=request.session.get("slogin") if not slogin: return redirect("/login_session/") susername=request.session.get("susername") name="123" shangpin = "香蕉" shangpin_list = ["苹果", "荔枝", "榴莲"] return render(request, 'index.html', {'name': susername, 'shangpin': shangpin, 'shangpin_list': shangpin_list})