栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Django学习笔记(6-1 用户登录-1)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django学习笔记(6-1 用户登录-1)


  • users->views.py
#我们眉配置一个url,Django就会自动生成一个request放到我们的函数里面,并作为第一个参数
def login(request):
    #request.method前端发现后端的时候使用的是post还是get方法
    #用户登陆的时候使用post要安全些,我们首先判断使用的方法是否是POST,注意POST是大写的
    if request.method = ="POST":
 pass
    elif request.method=="GET":
 #不是post方法传递就返回登陆页面,让用户继续输入
 #{}中传递数据到模板,可直接在模板使用
 return render(request,"login.html",{})
  • 配置login页面的url

urls.py

from users.views import login
urlpatterns = [
    #这里是指向login函数所以不加括号,如果是使用函数就要写成login()
    url('^login/$',login,name='login')
]
  • pycharm中debug

打断点,debug模式运行,某行蓝色代表断点到了这一行。鼠标点击这一行上面的对象就会显示这个对象的值。控制台Variable显示的是蓝色行即断点所在处的变量值。F6单步调试。F8全速前进

  • 禁止访问403
    表单提交要csrf防范
{% csrf_token %}
  • 逻辑
def login(request):
    if request.method = ="post":
 #既然能进来,token验证就是通过了的
 #username,password默认为空
 #取值
 user_name = request.POST.get("username","")
 pass_word = request.POST.get("password","")
 #验证
 #需要from django.contrib.auth import authenticate
 #只需向authenticate传入user_name和pass_word就可以验证
 #成功获得一个对象,失败返回None
 #参数名称username和password是固定的
 user = authenticate(username=user_name,password=pass_word)
 #authenticate只是向数据库发起验证问用户名和密码是否正确,但是实际的登陆并没有完成
 if user is not None:
     #同样from django.contrib.auth import login
     #为什么这样就可以登陆了呢???
     #session和cookie的机制
     login(request,user)
     return render(request,"index.html")
     #x现在已经跳转到index页面了,有什么判断和逻辑就到index里面去做
     #django默认会把request和user注册到index.html页面中来的
    elif request.method=="GET":
 return render(request,"login.html",{})
  • index.html中的逻辑判断
    Django当然不希望在html页面写python代码,所以提供了方法
{% if request.user.is_authenticated %}
    代码1
    {% else %}
    代码2
{% endif %}

可见,user其实也被放到了request里面,并且还多了一个is_authenticated方法

if user is not None:
    login(request,user)
    return render(request,"index.html")
else:
    return render(request,"login.html")
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/225823.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号