开发者

Why User model inheritance doesn't work properly?

开发者 https://www.devze.com 2022-12-20 03:11 出处:网络
I\'m trying to use a User model inheritance in my django application. Model looks like this: from django.contrib.auth.models import User, UserManager

I'm trying to use a User model inheritance in my django application. Model looks like this:

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

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

and authentication backend looks like this:

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

But if I'm trying to authenticate - there is an "MyUser matching query does not exist" error on the self.user_class.objects.get(username = username) call. It looks like admin user created on base syncing (I'm using sqlite3) stores into User model instead of MyUser (username and password are right). Or it's something different?

What I'm doing wrong? This is an example from http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/


Contrary to what the blog post you linked to says, storing this kind of data in a profile model is still the recommended way in Django. Subclassing User has all kinds of problems, one of which is the one you are hitting: Django has no idea you have subclassed User and happily creates and reads User models within the Django code base. The same is true for any other 3rd party app you might like to use.

Have a look at this ticket on Django's issue tracker to get some understanding of the underlying problems of subclassing User

0

精彩评论

暂无评论...
验证码 换一张
取 消