【发布时间】: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