【问题标题】:How to configure two AUTH_USER_MODEL in Django Authentication如何在 Django Authentication 中配置两个 AUTH_USER_MODEL
【发布时间】:2016-02-02 16:21:19
【问题描述】:

我正在使用 django 的身份验证来登录用户。但我有两个模型,authenticate 方法将检查用户凭据。一个是ApplicationUser,另一个是SystemUser,我已经制作了其中一个,效果很好:

models.py

class UserManager(BaseUserManager):
    def create_user(self, email, password=None):
        """
        Creates and saves a User with the given username and password.
        """
        ....
        return user

    def create_superuser(self, email, password):        
        ...
        return user


class ApplicationUser(AbstractBaseUser):
    application_user_id = models.AutoField(primary_key=True)
    ....
    ....

views.py

def login_view(request):
     ...
     user = authenticate(username = email, password = password)
     if user is not None:
         ...
         login(request, user)
         ....
         ....

我遇到了这个问题并得到了here,但我无法解决这个问题。

我的问题:

  1. 我如何指定两个AUTH_USER_MODEL,到目前为止我已经设置 ApplicationUserAUTH_USER_MODEL

  2. 即使我以某种方式指定 两个AUTH_USER_MODELauthenticatelogin 功能如何 知道在哪里(ApplicationUserSystemUser)匹配凭据并为用户创建会话 相应地

【问题讨论】:

    标签: python django django-authentication


    【解决方案1】:

    在你的 settings.py 中设置

    AUTH_USER_MODEL = 'yourapp.YouCustomUserModel'
    

    然后让 django 完成剩下的工作。

    如果你想拥有其他用户模型,你需要从你选择的AUTH_USER_MODEL扩展它们

    【讨论】:

    • 我已经使用 ApplicationUser 完成了该操作,这是我的 CustomUserModel。我该如何为SystemUser 指定呢?
    • @Sibtain 你只能有一个 auth 模型,如果你想从你的主 UserModel 派生其他模型,你需要扩展你的 AUTH USER MODEL。
    • 你能举个粗略的例子吗?
    猜你喜欢
    • 2021-01-22
    • 1970-01-01
    • 2015-07-28
    • 2022-07-19
    • 2021-08-07
    • 2019-08-16
    • 1970-01-01
    • 2016-10-17
    • 2021-09-28
    相关资源
    最近更新 更多