Understanding the Django 1.7 permissions system

Asked

Viewed 916 times

3

I have an app called forms_and_models which I use for study. In documentation of Django 1.7 says that:

Assuming you have an application whose app_label is foo and a model called Bar, to test basic permissions, you must use:

  • to add: user.has_perm('foo.add_bar')
  • to change: user.has_perm('foo.change_bar')
  • to delete: user.has_perm('foo.delete_bar')

Through the administrator, I added the permission: forms_and_models | Author | Can add Author to my user. Following the documentation template, I deduced that to test whether a user has permission to add an author, I could run the following code:

"""O usuário abaixo existe e é o que eu configurei a permissão acima""" user = User.objects.get(username='junior') user.has_perm('forms_and_models.add_author')

However this line of code always returns false. What I’m missing goes unnoticed over the permissions system?

  • I tested your code here and it seems to work correctly (I used Django 1.4 however, but the result should be the same). Try user.get_all_permissions() and see what happens. By the way, is this user a superuser or not, team member or not, active or not? (for example, if it is inactive, get_all_permissions will list permissions correctly, but has_perm will return False)

  • @mgibsonbr is active yes, it is not a superuser nor a member of the team. The result of user.get_all_permissions() returns set(). Any more information I can give?

  • I have no idea what might be going on, so... :( On my test, user.get_all_permissions() gave set([u'forms_and_models.add_author']). When you return there in admin, appears this permission to your user?

  • Yes, I can save whatever permissions are for that user, only the command line will not :(

  • 1

    Dumb question: You closed the command line and opened it again (or at least picked up the BD user again in a new query get) after saving the user via admin?

  • 1

    @mgibsonbr found what was wrong and answered my question, take a look down there. After you tested my code and everything went well, it came to mind that I should test with the Python 2 shell by Manage.py (i was starting with Python 3). Thanks for the help :)

Show 1 more comment

1 answer

1

I figured out what was going on. The problem was just that I was starting the interactive terminal shell using Python 3, that way: python3 manage.py shell

When I opened using the command ./manage.py shell, which uses the file shebang Manage.py, everything happened according to the documentation. Now permissions are listed normally. I’ve never had problems like this using Python 3 to start the shell. Go and understand.

Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.