Django - user permissions to certain views?


From the admin I see that you can allocate permissions to a user or a user group to :allow add, change or delete data from a model.

That is great, but I also need to allow a user or a user group to access or not a group of views. I have certain type of services on my web site so I want to allow some users to access a certain services (pages/views) but not others.

So how can I allow certain users/user groups access to certain views? Thank you!

1/4/2011 7:11:36 PM

Accepted Answer

Users that cannot add or change etc. a certain model, will not be able to see it in the admin.

If we are talking about your custom created views then you could create something which checks a user for a permission and returns a 404 if they do not have that permission. Permissions are linked to models and a group can be assigned various permissions.

You can add a permission to a model like this:

# myproject/myapp/

class MyModel(models.Model):
    class Meta:
        permissions = (
            ('permission_code', 'Friendly permission description'),

Then you can check a if a user has permission like this:

@user_passes_test(lambda u: u.has_perm('myapp.permission_code'))
def some_view(request):
    # ...

Using permissions you can then easily add or remove them from users and groups simply using the admin interface.

1/4/2011 7:44:51 PM

You need to manage that manually, but it's pretty easy. Presumably there's an attribute that determines whether or not a group has permission to see a view: then you just decorate that view with either the permission_required decorator, if it's a simple question of whether the user has a particular Permission, or user_passes_test if it's a bit more complicated:

@user_passes_test(lambda u: u.is_allowed_to_see_view_myview())
def myview(request):

assuming that is_allowed_to_see_view_myview is some sort of method on the User object.

The authentication docs are pretty comprehensive.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow