zoukankan      html  css  js  c++  java
  • django 修改默认的user表和默认的认证系统

    django的功能非常强大,但是自带的user表很多情况下并不满足我们的需求,因此我们需要修改其默认的user表,并且把用username登录改成用email登录

    第一步,创建自己的user表,在创建的app下的models中

    from django.contrib.auth.models import AbstractUser
    from django.db import models # Create your models here.
    class UserProfile(AbstractUser): nick_name = models.CharField(max_length=50, verbose_name='昵称', default='') birthday = models.DateField(null=True, blank=True, verbose_name='生日') gender = models.CharField(max_length=6, choices=(('male', ''), ('female', '')), default='female', 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(max_length=100, upload_to='image/%Y/%m', default='image?default.png', verbose_name='头像')
      class Meta:
      verbose_name = '用户信息'
      verbose_name_plural = verbose_name
      def __str__(self):
      return self.username

    因为django的user表也是继承自AbstractUser,所以我们也这样做

    然后修改下setting,添加

    # UserProfile 覆盖了 django 内置的 user 表
    AUTH_USER_MODEL = 'users.UserProfile'

    appname.userProfile

    接着修改认证系统

    
    
    from django.contrib.auth import authenticate, login, logout
    from django.contrib.auth.backends import ModelBackend
    from django.db.models import Q
    from models import UserProfile

    #
    让用户可以用邮箱登录 # setting 里要有对应的配置 class CustomBackend(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

    记得引入models中创建的表

    # AUTH 方法(支持邮箱登录)
    AUTHENTICATION_BACKENDS = ('users.views.CustomBackend',)

    setting中加入该方法

    完成

  • 相关阅读:
    B-Suffix Array
    1 or 2
    Boundary
    Fake Maxpooling
    Cover the Tree
    Omkar and Circle
    20.5.31
    Yet Another Yet Another Task
    Codeforces Round #373 (Div. 2)E. Sasha and Array +线段树+矩阵快速幂
    2018 Multi-University Training Contest 2(Naive Operations ) hdu6315
  • 原文地址:https://www.cnblogs.com/lgh344902118/p/7047147.html
Copyright © 2011-2022 走看看