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模型 from django.contrib.auth.models 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 from django.contrib.auth import authenticate,login from django.contrib.auth.backends import ModelBackend from django.db.models 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 = UserProfile.objects.get(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): if request.method == 'POST': user_name = request.POST.get('username','') pass_word = request.POST.get('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: return render(request,'login.html',{'msg':'用户未激活'}) else: return render(request, 'login.html',{'mgs':'用户名或密码错误'}) elif request.method == 'GET': return render(request,'login.html')
settings.py
# AUTH 方法(支持邮箱登录) AUTHENTICATION_BACKENDS = ('users.views.CustomBackend',)
到此,我们就支持邮箱和用户名登录了