Django 登录逻辑和配置邮箱登录
1.登录逻辑
在应用下的views 中定义登录逻辑
| 1 | # -*- coding:utf-8 -*- | 
- 这里使用基于类的视图来写登陆逻辑,登录视图继承 视图,里面有 get 和 post 方法,我们要复写,同时要带上请求参数 request 。 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 - 在客户端post过来的表单数据后,使用自己定义的form对数据进行校验,检验数据是否合法,里面有一些参数可选。
 - 在对表单进行校验后,如果数据合法,则获取请求参数中的用户名和密码,然后使用 django 提供的authenticate 方法验证账户和密码正确性。
 - 在得到验证后的数据后如果正确,在调用 django 的 login 方法,将 user 对象进行登录,让后返回登录后的页面;如果错误则返回登录的页面,同时放入错误信息。
 2.邮箱登录
 ```python
 # -*- coding:utf-8 -*-
 from django.contrib.auth import authenticate
 from django.contrib.auth.backends import ModelBackend
 from django.db.models import Q
 from .models import UserProfile
 class CustmoBackend(ModelBackend):
 def authenticate(self, username=None, password=None, **kwargs):
 try:
 user = UserProfile.objects.get(Q(username=username)|Q(email=username))
 if user.check_password(password):
 return user
 except Exception as e:
 return None