当Django`User`的主键是`CharField`时登录时出错

时间:2014-01-26 12:53:16

标签: python django many-to-many django-users

我想使用CharField作为Django User的主键,并为其添加一些额外的字段。所以,我扩展了AbstractUser模型,如下所示:

class User(AbstractUser):
    id = models.CharField(primary_key=True, max_length=32, default=str(uuid.uuid4()).replace('-', ''))
    Telephone = models.CharField('Telephone', max_length=100, blank=True, null=True)
    Mobile = models.CharField('Mobile', max_length=100, blank=True, null=True)

这非常适合在User上进行CRUD操作。但是当我尝试以超级用户状态为False的用户身份登录时,会出现以下错误:

Environment:


Request Method: GET
Request URL: http://localhost:8000/admin/

Django Version: 1.5.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.humanize',
 'UserApp',)
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in         get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in wrapper
  219.                 return self.admin_view(view, cacheable)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
  91.                     response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  89.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
  202.             return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  89.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in index
  346.             has_module_perms = user.has_module_perms(app_label)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py" in has_module_perms
  367.         return _user_has_module_perms(self, app_label)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py" in _user_has_module_perms
  288.             if backend.has_module_perms(user, app_label):
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/backends.py" in has_module_perms
  59.         for perm in self.get_all_permissions(user_obj):
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/backends.py" in get_all_permissions
  45.             user_obj._perm_cache.update(self.get_group_permissions(user_obj))
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/backends.py" in get_group_permissions
  35.                 perms = Permission.objects.filter(**{user_groups_query: user_obj})
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in filter
  155.         return self.get_query_set().filter(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in filter
  655.         return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _filter_or_exclude
  673.             clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py" in add_q
  1266.                             can_reuse=used_aliases, force_having=force_having)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py" in add_filter
  1197.                 connector)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/where.py" in add
  71.             value = obj.prepare(lookup_type, value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/where.py" in prepare
  339.             return self.field.get_prep_lookup(lookup_type, value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py" in get_prep_lookup
  143.             return self._pk_trace(value, 'get_prep_lookup', lookup_type)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py" in _pk_trace
  216.         v = getattr(field, prep_func)(lookup_type, v, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py" in get_prep_lookup
  322.             return self.get_prep_value(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py" in get_prep_value
  555.         return int(value)

Exception Type: ValueError at /admin/
Exception Value: invalid literal for int() with base 10: 'c4cadcd0538e45dcaee946d079e11be5'

我做了一些搜索,发现Django做了一个反向的多对多查询,以便在非超级用户登录时查找权限。我检查了反向多对多查询的工作情况,当模型有一个CharField作为主键,发现了类似的错误。请参阅此票证https://code.djangoproject.com/ticket/21879

是否有解决此问题的方法?

2 个答案:

答案 0 :(得分:1)

请注意,contrib.auth软件包的doc明确指定自定义用户模型必须具有整数primaray密钥:

https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#specifying-a-custom-user-model

  

Django希望您的自定义用户模型达到最低限度   要求。

Your model must have an integer primary key.
(...)

这里显而易见的解决方案是将id保留为整数,并添加uuid字段和unique约束。否则你将不得不叉contrib.auth,但我不确定它会是一个好主意......

答案 1 :(得分:1)

更新

在Django 1.6上测试它可以工作并接受CharField作为id


你可以做的是使用Django的AbstractBaseUser编写你自己的自定义模型,并编写你自己的PermissionsMixin,虽然这听起来很复杂但你真的不需要复制Django的代码来自django.contrib.auth并更改一行代码

问题行是get_group_permissions函数中的django.contrib.auth.backends中的行:

perms = Permission.objects.filter(**{user_groups_query: user_obj})

您可以将其更改为:

perms = Permission.objects.filter(**{user_groups_query + '__pk': user_obj})

虽然我django 1.6解决了这个问题

为清楚起见,完整的解决方案如下: 的 models.py     来自django.contrib.auth导入AbstractBaseUser     来自权限导入MyPermissionsMixin

class UserProfile(AbstractBaseUser, MyPermissionsMixin):
    id = models.CharField(primary_key=True, max_length=32, default=str(uuid.uuid4()).replace('-', ''))
    Telephone = models.CharField('Telephone', max_length=100, blank=True, null=True)
    Mobile = models.CharField('Mobile', max_length=100, blank=True, null=True)
    username = models.CharField(_('username'), max_length=30, unique=True,
                                help_text=_('Required. 30 characters or fewer. Letters, numbers and '
                                            '@/./+/-/_ characters'),
                                validators=[
                                    validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'),
                                                              'invalid')
                                ])
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    is_staff = models.BooleanField(_('staff status'), default=False,
                                   help_text=_('Designates whether the user can log into this admin '
                                               'site.'))
    is_active = models.BooleanField(_('active'), default=True,
                                    help_text=_('Designates whether this user should be treated as '
                                                'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.username)

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        "Returns the short name for the user."
        return self.first_name

    def email_user(self, subject, message, from_email=None):
        """
        Sends an email to this User.
        """
        send_mail(subject, message, from_email, [self.email])

    def get_profile(self):
        """
        Returns site-specific profile for this user. Raises
        SiteProfileNotAvailable if this site does not allow profiles.
        """
        warnings.warn("The use of AUTH_PROFILE_MODULE to define user profiles has been deprecated.",
                      PendingDeprecationWarning)
        if not hasattr(self, '_profile_cache'):
            from django.conf import settings

            if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
                raise SiteProfileNotAvailable(
                    'You need to set AUTH_PROFILE_MODULE in your project '
                    'settings')
            try:
                app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
            except ValueError:
                raise SiteProfileNotAvailable(
                    'app_label and model_name should be separated by a dot in '
                    'the AUTH_PROFILE_MODULE setting')
            try:
                model = models.get_model(app_label, model_name)
                if model is None:
                    raise SiteProfileNotAvailable(
                        'Unable to load the profile model, check '
                        'AUTH_PROFILE_MODULE in your project settings')
                self._profile_cache = model._default_manager.using(
                    self._state.db).get(user__id__exact=self.id)
                self._profile_cache.user = self
            except (ImportError, ImproperlyConfigured):
                raise SiteProfileNotAvailable
        return self._profile_cache

<强> permissions.py 创建一个名为permissions.py的新文件,并在此处存储MyPermissionsMixin

    from __future__ import unicode_literals
    from django.contrib.auth import get_user_model
    from django.contrib.auth.models import Group, Permission

    from django.db import models
    from django.utils.translation import ugettext_lazy as _
    from django.utils import timezone

    from django.contrib import auth
    # UNUSABLE_PASSWORD is still imported here for backwards compatibility
    from django.contrib.auth.signals import user_logged_in


    def update_last_login(sender, user, **kwargs):
        """
        A signal receiver which updates the last_login date for
        the user logging in.
        """
        user.last_login = timezone.now()
        user.save(update_fields=['last_login'])


    user_logged_in.connect(update_last_login)


    class SiteProfileNotAvailable(Exception):
        pass


    def get_group_permissions(user_obj, obj=None):
        """
        Returns a set of permission strings that this user has through his/her
        groups.
        """
    if user_obj.is_anonymous() or obj is not None:
        return set()
    if not hasattr(user_obj, '_group_perm_cache'):
        if user_obj.is_superuser:
            perms = Permission.objects.all()
        else:
            user_groups_field = get_user_model()._meta.get_field('groups')
            user_groups_query = 'group__%s' % user_groups_field.related_query_name()
    try:
        perms = Permission.objects.filter(**{user_groups_query: user_obj})
    except:
        perms = Permission.objects.filter(**{user_groups_query + '__pk': user_obj})
    perms = perms.values_list('content_type__app_label', 'codename').order_by()
    user_obj._group_perm_cache = set(["%s.%s" % (ct, name) for ct, name in perms])
    return user_obj._group_perm_cache


def get_all_permissions(user_obj, obj=None):
    if user_obj.is_anonymous() or obj is not None:
        return set()
    if not hasattr(user_obj, '_perm_cache'):
        user_obj._perm_cache = set(
            ["%s.%s" % (p.content_type.app_label, p.codename) for p in user_obj.user_permissions.select_related()])
        user_obj._perm_cache.update(get_group_permissions(user_obj))
    return user_obj._perm_cache


def has_perm(user_obj, perm, obj=None):
    if not user_obj.is_active:
        return False
    return perm in get_all_permissions(user_obj, obj)


def has_module_perms(user_obj, app_label):
    """
    Returns True if user_obj has any permissions in the given app_label.
    """
    if not user_obj.is_active:
        return False
    for perm in get_all_permissions(user_obj):
        if perm[:perm.index('.')] == app_label:
            return True
    return False


def get_user(user_id):
    try:
        UserModel = get_user_model()
        return UserModel._default_manager.get(pk=user_id)
    except UserModel.DoesNotExist:
        return None


# A few helper functions for common logic between User and AnonymousUser.
def _user_get_all_permissions(user, obj):
    permissions = set()
    for backend in auth.get_backends():
        if hasattr(backend, "get_all_permissions"):
            if obj is not None:
                permissions.update(get_all_permissions(user, obj))
            else:
                permissions.update(get_all_permissions(user))
    return permissions


def _user_has_perm(user, perm, obj):
    for backend in auth.get_backends():
        if hasattr(backend, "has_perm"):
            if obj is not None:
                if has_perm(user, perm, obj):
                    return True
            else:
                if has_perm(user, perm):
                    return True
    return False


def _user_has_module_perms(user, app_label):
    for backend in auth.get_backends():
        if hasattr(backend, "has_module_perms"):
            if has_module_perms(user, app_label):
                return True
    return False


class MyPermissionsMixin(models.Model):
    """
    A mixin class that adds the fields and methods necessary to support
    Django's Group and Permission model using the ModelBackend.
    """
    is_superuser = models.BooleanField(_('superuser status'), default=False,
                                       help_text=_('Designates that this user has all permissions without '
                                                   'explicitly assigning them.'))
    groups = models.ManyToManyField(Group, verbose_name=_('groups'),
                                    blank=True, help_text=_('The groups this user belongs to. A user will '
                                                            'get all permissions granted to each of '
                                                            'his/her group.'))
    user_permissions = models.ManyToManyField(Permission,
                                              verbose_name=_('user permissions'), blank=True,
                                              help_text='Specific permissions for this user.')

    class Meta:
        abstract = True

    def get_group_permissions(self, obj=None):
        """
        Returns a list of permission strings that this user has through his/her
        groups. This method queries all available auth backends. If an object
        is passed in, only permissions matching this object are returned.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_group_permissions"):
                if obj is not None:
                    permissions.update(get_group_permissions(self,
                                                                     obj))
                else:
                    permissions.update(get_group_permissions(self))
        return permissions

    def get_all_permissions(self, obj=None):
        return _user_get_all_permissions(self, obj)

    def has_perm(self, perm, obj=None):
        """
        Returns True if the user has the specified permission. This method
        queries all available auth backends, but returns immediately if any
        backend returns True. Thus, a user who has permission from a single
        auth backend is assumed to have permission in general. If an object is
        provided, permissions for this specific object are checked.
        """

        # Active superusers have all permissions.
        if self.is_active and self.is_superuser:
            return True

        # Otherwise we need to check the backends.
        return _user_has_perm(self, perm, obj)

    def has_perms(self, perm_list, obj=None):
        """
        Returns True if the user has each of the specified permissions. If
        object is passed, it checks if the user has all required perms for this
        object.
        """
        for perm in perm_list:
            if not self.has_perm(perm, obj):
                return False
        return True

    def has_module_perms(self, app_label):
        """
        Returns True if the user has any permissions in the given app label.
        Uses pretty much the same logic as has_perm, above.
        """
        # Active superusers have all permissions.
        if self.is_active and self.is_superuser:
            return True

        return _user_has_module_perms(self, app_label)