Unable to set user permissions in Django

I am trying to configure some user permissions for a Django application but cannot make it work. The official documentation is a bit sparse and doesn't mention (at least what I can find) how to actually set the permission? Based on a few third-party tutorials that I found, I extended the User class and it seems to work fine:

from django.db import models from django.contrib.auth.models import User,UserManager class CustomUser(User): custom_field = models.CharField(max_length=250) objects = UserManager() class Meta: permissions = ( ('is_custom','Has a Custom Permission'), ) 

When I try to set the resolution, it does not work:

 >>> from project.custauth.models import CustomUser >>> from django.contrib.auth.models import User, Permission >>> user = CustomUser.objects.get(username='new.user') >>> user <CustomUser: new.user> >>> custom_permission = Permission.objects.get(codename="is_custom") >>> custom_permission <Permission: custauth | custom user | Has a Custom Permission> >>> custom_permission.save() >>> user.user_permissions.add(custom_permission) >>> user.save() >>> user.has_perm(custom_permission) False >>> user.get_all_permissions() set([]) 

Any ideas on what I'm doing wrong? I am using Django 1.2.1 with Python 2.4.3. All input is evaluated ...

+6
python django permissions
source share
2 answers

I tested your code (Python 2.6.2, Django 1.2.1) and everything worked as expected. Can you write unit test to implement the same piece of code?

On the side note, user.has_perm(custom_permission) does not return True . Try user.has_perm('app.is_custom') .

Update

The following is a snippet of code:

 In [1]: from app.models import CustomUser In [2]: from django.contrib.auth.models import User, Permission In [3]: user = CustomUser.objects.get(username = 'new.user') In [4]: custom_permission = Permission.objects.get(codename='is_custom') In [5]: user.user_permissions.add(custom_permission) In [6]: user.save() In [7]: user.has_perm(custom_permission) Out[7]: False In [8]: user.has_perm('app.is_custom') Out[8]: True In [9]: user.get_all_permissions() Out[9]: set([u'app.is_custom']) 
+1
source share

I ran a few more tests on another platform and was able to reproduce your results. After more digging, I found that the problem was with the authentication database, not with the permissions themselves.

Thanks for your help Manoah.

0
source share

All Articles