Django学习系列之重写User模型和登录验证
重写User模型
Django内置的User模型可能不适合某些项⽬,我们可能要基于内置的添加⼀些字段
创建users app
startapp users
修改settings.py配置⽂件,覆盖默认的user模型
settings.py
添加以下内容
'''是app的名称,和models⾥的class名称(表名)'''
AUTH_USER_MODEL = "users.UserProfile"
编写users app下的models.py
models.py
from django.db import models
#引⽤内置的user模型
dels import  AbstractUser
# Create your models here.
#集成内置的user模型,并添加新的字段
class UserProfile(AbstractUser):
nick_name = models.CharField(max_length=50,verbose_name='昵称',default='')
birday = models.DateField(null=True,blank=True,verbose_name='⽣⽇')
choice_gender = (
("male","男"),
("female","⼥"),
)
gender = models.CharField(choices=choice_gender,default='female',max_length=5,verbose_name='性别')
address = models.CharField(max_length=100,default='',verbose_name='地址')
mobile = models.CharField(max_length=11,null=True,blank=True,verbose_name='⼿机号')
image = models.ImageField(upload_to='image/%Y/%m',default='image/default.png',max_length=100)
class Meta:
verbose_name = "⽤户信息"
verbose_name_plural = "⽤户信息"
def __unicode__(self):
return self.username
⽣成数据表
makemigrtions
migrate
登录数据库查看
⾃定义登录验证
由于⽤户表中带email字段,想实现通过email和⽤户名都能登录,就需要重写django authenticate(登录验证)⽅法
views.py
from django.shortcuts import render
ib.auth import  authenticate,login
ib.auth.backends import ModelBackend
from dels import Q
from .models import UserProfile,EmailVerfyRecord,Banner
#重写的authenticate登录验证
class CustomBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
try:
#Q⽅法的作⽤是或的意思,acc_login⽅法把username和password传过来,如果以username为条件去库⾥查没查到的话,就以email为条件去库⾥查(因为传过来的username 可能是⽤户名或者email)            user = (Q(username=username)|Q(email=username))
#检测username和password是否匹配
if user.check_password(password):
return user
except Exception as e:
return None
#登录⽅法
def acc_login(request):
hod == 'POST':
user_name = ('username','')
pass_word = ('password','')
user = authenticate(username=user_name,password=pass_word) if user is not None:
if user.is_active:
login(request,user)
return render(request,'index.html')
else:
django怎么学return render(request,'login.html',{'msg':'⽤户未激活'}) else:
return render(request, 'login.html',{'mgs':'⽤户名或密码错误'})    hod == 'GET':
return render(request,'login.html')
settings.py
# AUTH ⽅法(⽀持邮箱登录)
AUTHENTICATION_BACKENDS = ('users.views.CustomBackend',)到此,我们就⽀持邮箱和⽤户名登录了

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。