setting
添加配置
AUTHENTICATION_BACKENDS = (
'users.views.CustomBackend',
# 'django.contrib.auth.backends.ModelBackend',
)
users.views.CustomBackend
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend, BaseBackend
from django.db.models import Q
from django.shortcuts import render
User = get_user_model()
class CustomBackend(BaseBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try:
user = User.objects.get(Q(username=username) | Q(mobile=username))
if user.check_password(password):
return user
except Exception as e:
return None
UserModel的配置
AUTH_USER_MODEL = 'users.UserProfile'
users.model.UserProfile
from datetime import datetime
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserProfile(AbstractUser):
"""
用户
"""
name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名")
birthday = models.DateField(null=True, blank=True, verbose_name="出生年月")
gender = models.CharField(max_length=6, choices=(("male", u"男"), ("female", "女")), default="female", verbose_name="性别")
mobile = models.CharField(null=True, blank=True, max_length=11, verbose_name="电话")
email = models.EmailField(max_length=100, null=True, blank=True, verbose_name="邮箱")
class Meta:
verbose_name = "用户"
verbose_name_plural = verbose_name
def __str__(self):
return self.username
- 关键点 继承 AbstractUser
配置 admin.py
from django.contrib import admin
# Register your models here.
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(UserAdmin,User)
0则评论给“Django自定义用户登录”