自定义UserModel
环境:django 1.9.11+python 2.7
from django.contrib.auth.models import AbstractUser class UserProfile(AbstractUser): // AbstractUser是Django自带的UserModel父类,在继承的基础上添加新的用户字段 nick_name = models.CharField(max_length=50, verbose_name=u"昵称", default="") birday = models.DateField(verbose_name=u"生日", null=True, blank=True) gender = models.CharField(max_length=7, choices=(("male", u"男"),("female", u"女")), default="female") address = models.CharField(max_length=100, default="") mobile = models.CharField(max_length=11, null=True, blank=True) image = models.ImageField(upload_to="image/%Y/%m", default=u"image/default.png", max_length=100) class Meta: verbose_name = "用户信息" verbose_name_plural = verbose_name def __unicode__(self): return self.username settings.py AUTH_USER_MODEL = "users.UserProfile" // 要让自定义UserModel生效,需要在settings文件中声明
自定义UserModel认证和登录
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 django.views.generic.base import View from .models import UserProfile class CustomBackend(ModelBackend): // 首先需要重写认证后台的authenticate方法,因为默认的authenticate方法验证的是自带的UserModel def authenticate(self, username=None, password=None, **kwargs): try: user = UserProfile.objects.get(Q(username=username)|Q(email=username)) // Q这个函数表达一种或的关系,即账号既可以是用户名也可以是邮箱 if user.check_password(password): // 之前继承的AbstractUser中自带了一个check_password方法,作用是将密码转换为密文进行验证 return user // authenticate方法取得对象并验证密码成功后会返回user对象 except Exception as e: // get()方法当获取不到值时会出现异常,check_password()不成功也会有异常 return None // 出现异常则返回None class LoginView(View): def get(self, request): return render(request, "login.html", {}) def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get("username", "") pass_word = request.POST.get("password", "") user = authenticate(username=user_name, password=pass_word) // 这里会调用重写后的authenticate方法 if user is not None: login(request, user) // 调用login()方法进行登录,实际上是对request进行一些操作,把user写入request return render(request, "index.html") else: return render(request, "login.html", {"msg": u"用户名或密码错误", "login_form":login_form}) settings.py // 对于自定义认证后台,同样需要在settings文件中进行声明 AUTHENTICATION_BACKENDS = ( ‘users.views.CustomBackend‘, )
原文地址:https://www.cnblogs.com/Peter2014/p/8596811.html
时间: 2024-10-08 15:11:35