Search code examples
pythondjangomany-to-manydjango-users

Error while logging in when primary key of Django `User` is a `CharField`


I wanted to use a CharField as primary key for Django User and add some extra fields to it. So, I extended AbstractUser model as given below:

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)

This works perfectly for doing CRUD operations on User. But when I try to login as a User whose Superuser Status is False, following error shows up:

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'

I did some search a found that Django does a reverse many-to-many query to find out permissions when a non-superuser logs in. I checked working of reverse many-to-many query is case of when models has a CharField as primary key and found similar error. Please refer to this ticket https://code.djangoproject.com/ticket/21879.

Is there a fix for this problem?


Solution

  • Update:

    Tested on Django 1.6 it works and accepts a CharField as an id


    What you can do is write your own custom models using Django's AbstractBaseUser as well as write your own PermissionsMixin, although this sounds complicated it really ins't you just need to copy Django's code from the django.contrib.auth and change a single line of code

    the problem line is the line, in django.contrib.auth.backends in the get_group_permissions function:

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

    you can change that to something like:

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

    Although I django 1.6 solves this problem

    For clarity the complete solutions is as follows: models.py from django.contrib.auth import AbstractBaseUser from permissions import 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 create a new file called permissions.py and store MyPermissionsMixin here

        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)