django实现用户登陆功能详解


Posted in Python onDecember 11, 2017

django实现用户登陆功能详解

简介:

Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位。许多成功的网站和APP都基于Django。

Django是一个开放源代码的Web应用框架,由Python写成。

Django遵守BSD版权,初次发布于2005年7月, 并于2008年9月发布了第一个正式版本1.0 。

Django采用了MVC的软件设计模式,即模型M,视图V和控制器C。

用户名密码登陆实现:

在apps.users下找到views.py文件:
以下代码重写了authenticate()方法,方便用户扩展功能,比如邮箱验证登陆等。
在setting.py中重载一个变量:

AUTHENTICATION_BACKENDS = ('users.views.CustomBackend',)

from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
# 继承View 实现基于类的用户登陆
from django.views.generic.base import View 
from .models import UserProfile
# 重写 authenticate 登陆验证方法
class CustomBackend(ModelBackend):
  def authenticate(self, username=None, password=None, **kwargs):
    try:
     # 验证用户名或邮箱, Q提供了一个对象间的或(与&)运算
    user=UserProfile.objects.get(Q(username=username) | Q(email=username))
      # 后台密码为暗文,传入的密码为明文, 所以需要使用check_password()方法验证密码
      if user.check_password(password):
        # 验证成功返回user对象
        return user 
    # 登陆失败返回None
    except Exception as e:
      return None

继承django.views.generic.base中的View类,根据method的不同,对应实现GET和POST的不同处理,一般POST为验证用户登陆,在此基础上还可以添加form处理,减少错误提交,减少对服务器的访问次数。

# 基于类实现用户登陆
class LoginView(View):
  # 会根据 method 调用 post或者get方法
  def get(self, request):
    # 如果method为 GET 重新返回登陆页面
    return render(request, "login.html", {})

  def post(self, request):
    # 验证每个字段是否合法
    login_form = LoginForm(request.POST)
    # 对每个字段进行预处理,如果不合法,直接提示错误信息
    pre_check = login_form.is_valid()
    # 如果合法
    if pre_check:
      # 从POST中取出用户名和密码
      user_name = request.POST.get("username", "")
      if UserProfile.objects.filter(email=user_name):
        return render(request, "register.html", {"register_form": register_form, "msg": "用户已经存在"})
      pass_word = request.POST.get("password", "")
      # 此处为上面重写的authenticate方法
      user = authenticate(username=user_name, password=pass_word)
      if user is not None:   # 如果成功返回对象,失败返回None
        login(request, user) # 调用login方法登陆账号
        return render(request, "index.html")
      else:
        # 登陆失败
        return render(request, "login.html", {"msg":u"用户名或密码错误"})
    else:
      # form验证失败,给出错误信息
      return render(request, "login.html", {"login_form":login_form})

要实现form处理功能,在form.py中定义具体要求即可:

from django import forms
# 继承forms.Form
class LoginForm(forms.Form):
  # 如果为空则报错
  username = forms.CharField(required=True)
  # 同时也可以设定长度限制min_length、max_length
  password = forms.CharField(required=True, min_length=5)

html中要写出登陆出错之后,信息提示的逻辑:

<div class="form-group marb20 {% if login_form.errors.username %}errorput{% endif %}">

form验证错误的提示:

<div class="error btns login-form-tips" id="jsLoginTips">{% for key,error in login_form.errors.items %}{{ error }}{% endfor %} {{ msg }}</div>

总结

以上就是本文关于django实现用户登陆功能详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
简单的编程0基础下Python入门指引
Apr 01 Python
修改Python的pyxmpp2中的主循环使其提高性能
Apr 24 Python
用Python计算三角函数之acos()方法的使用
May 15 Python
在Python中操作列表之List.append()方法的使用
May 20 Python
Python调用系统底层API播放wav文件的方法
Aug 11 Python
利用Python-iGraph如何绘制贴吧/微博的好友关系图详解
Nov 02 Python
简单了解OpenCV是个什么东西
Nov 10 Python
Python基础之循环语句用法示例【for、while循环】
Mar 23 Python
Windows系统Python直接调用C++ DLL的方法
Aug 01 Python
PyQt5中多线程模块QThread使用方法的实现
Jan 31 Python
python 实现性别识别
Nov 21 Python
一篇文章带你搞懂Python类的相关知识
May 20 Python
Python通过Django实现用户注册和邮箱验证功能代码
Dec 11 #Python
Python实现冒泡排序的简单应用示例
Dec 11 #Python
Python最火、R极具潜力 2017机器学习调查报告
Dec 11 #Python
python使用pil进行图像处理(等比例压缩、裁剪)实例代码
Dec 11 #Python
让Python更加充分的使用Sqlite3
Dec 11 #Python
pandas中Timestamp类用法详解
Dec 11 #Python
Python排序搜索基本算法之插入排序实例分析
Dec 11 #Python
You might like
php中神奇的fastcgi_finish_request
2011/05/02 PHP
深入探讨:Nginx 502 Bad Gateway错误的解决方法
2013/06/03 PHP
php获取textarea的值并处理回车换行的方法
2014/10/20 PHP
PHP中isset与array_key_exists的区别实例分析
2015/06/02 PHP
Thinkphp5.0 框架视图view的比较标签用法分析
2019/10/12 PHP
Yii框架组件的事件机制原理与用法分析
2020/04/07 PHP
用jQuery扩展自写的 UI导航
2010/01/13 Javascript
js字母大小写转换实现方法总结
2013/11/13 Javascript
jquery实现省市select下拉框的替换(示例代码)
2014/02/22 Javascript
Juery解决tablesorter中文排序和字符范围的方法
2015/05/06 Javascript
JavaScript中var关键字的使用详解
2015/08/14 Javascript
JQuery日期插件datepicker的使用方法
2016/03/03 Javascript
javascript执行环境及作用域详解
2016/05/05 Javascript
jquery实现弹窗功能(窗口居中显示)
2017/02/27 Javascript
理解Angular的providers给Http添加默认headers
2017/07/04 Javascript
JS中定位 position 的使用实例代码
2017/08/06 Javascript
vue 组件中使用 transition 和 transition-group实现过渡动画
2019/07/09 Javascript
全局安装 Vue cli3 和 继续使用 Vue-cli2.x操作
2020/09/08 Javascript
JavaScript封装单向链表的示例代码
2020/09/17 Javascript
[42:24]完美世界DOTA2联赛PWL S2 LBZS vs FTD.C 第三场 11.27
2020/12/01 DOTA
Python进阶篇之字典操作总结
2016/11/16 Python
Python函数参数操作详解
2018/08/03 Python
Django model序列化为json的方法示例
2018/10/16 Python
Python中的Socket 与 ScoketServer 通信及遇到问题解决方法
2019/04/01 Python
python爬虫 execjs安装配置及使用
2019/07/30 Python
Python logging模块进行封装实现原理解析
2020/08/07 Python
jupyter notebook 写代码自动补全的实现
2020/11/02 Python
python tqdm实现进度条的示例代码
2020/11/10 Python
加拿大廉价机票预订网站:CheapOair.ca
2018/03/04 全球购物
个人职业生涯规划书1500字
2013/12/31 职场文书
大学军训感言200字
2014/02/26 职场文书
《微笑着面对生活》优秀演讲稿范文
2014/09/23 职场文书
农村党员干部承诺书
2015/05/04 职场文书
Java spring单点登录系统
2021/09/04 Java/Android
WINDOWS 64位 下安装配置mysql8.0.25最详细的教程
2022/03/22 MySQL
Golang日志包的使用
2022/04/20 Golang