【问题标题】:Why User model inheritance doesn't work properly?为什么用户模型继承不能正常工作?
【发布时间】:2010-02-16 16:28:52
【问题描述】:

我正在尝试在我的 django 应用程序中使用 User 模型继承。模型如下所示:

from django.contrib.auth.models import User, UserManager

class MyUser(User):
    ICQ = models.CharField(max_length=9)
    objects = UserManager()

身份验证后端如下所示:

import sys

from django.db import models
from django.db.models import get_model
from django.conf import settings
from django.contrib.auth.models import User, UserManager
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured

class AuthBackend(ModelBackend):
    def authenticate(self, email=None, username=None, password=None):
        try:            
            if email:
                user = self.user_class.objects.get(email = email)
            else:
                user = self.user_class.objects.get(username = username)

            if user.check_password(password):
                return user

        except self.user_class.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return self.user_class.objects.get(pk=user_id)
        except self.user_class.DoesNotExist:
            return None

    @property
    def user_class(self):
        if not hasattr(self, '_user_class'):
            self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
            if not self._user_class:
                raise ImproperlyConfigured('Could not get custom user model')
        return self._user_class

但如果我尝试进行身份验证 - self.user_class.objects.get(username = username) 上存在“MyUser 匹配查询不存在”错误强>调用。它看起来像在基本同步(我正在使用 sqlite3)上创建的管理员用户存储到 User 模型而不是 MyUser (用户名和密码是正确的)。还是有什么不同?

我做错了什么?这是来自http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/的示例

【问题讨论】:

    标签: python django inheritance django-models


    【解决方案1】:

    与您链接到的博客文章所说的相反,将这种数据存储在配置文件模型中仍然是 Django 中推荐的方式。子类化User 有各种各样的问题,其中之一就是您遇到的问题:Django 不知道您已经对User 进行了子类化,并愉快地在Django 代码库中创建和读取User 模型。对于您可能想使用的任何其他第 3 方应用程序也是如此。

    查看 Django 问题跟踪器上的 this ticket 以了解子类化 User 的潜在问题

    【讨论】:

    • 好的,谢谢,我已经尝试过了,因为这种用户模型扩展在 DjangoBook 的俄语翻译中被描述为一种好方法。不幸的是,正如我所见,事实并非如此。
    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2020-08-17
    • 2011-05-03
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    相关资源
    最近更新 更多