我想将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。
有解决此问题的方法吗?
更新:
在Django 1.6上进行了测试,它可以正常工作并接受CharField作为id
您可以做的是使用Django的AbstractBaseUser编写自己的自定义模型,以及编写自己的PermissionsMixin,尽管这听起来很复杂,但实际上并不是您只需要从django.contrib.auth复制Django的代码并更改一行即可。代码
问题行是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解决了这个问题
为了清楚起见,完整的解决方案如下:django.contrib.auth中的models.py从权限中导入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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句