Darwin Tech
Darwin Tech

Reputation: 18919

Django restrict views by User permissions which are editable in the Admin

I have a Django application where I need to restrict specific Views to subset of Users. I also want to be bale to edit which Users have this permission via the Django Admin. So in the admin I would like to be able to see all users and have a check box which can be checked to give permission to see this specific Views.

I believe the way to approach to this is to a permissions decorator on the Views in question:

from django.contrib.auth.decorators import permission_required

@login_required
@permission_required('user.can_view_restricted', login_url='/accounts/login/')
def Restrictedview(request, template_name='restricted.html'):
    ...
    # restricted stuff

Now I know I need to define this permission (in permissions.py?), and register it with the Admin. I am unsure of how to do this and how to properly associate the permission with a specific User instance. Should this be an extra field on 'User', or a separate model to hold model to hole Users and Permissions?

Upvotes: 3

Views: 7985

Answers (1)

Muhammad Saeed Arabi
Muhammad Saeed Arabi

Reputation: 66

You can read in details about django permissions in the docs https://docs.djangoproject.com/en/dev/topics/auth/default/#permissions-and-authorization

Basically Django permissions use the Permission model, which is found at django.contrib.auth.models, but for most applications you don't need to directly import or use that model.

By default Django creates 3 default permissions for any model you have in your app. If you have a model named MyModel in an app named myapp, then Django will create create_mymodel, change_mymodel, and delete_mymodel permissions by default.

You can check if the user has a certain permission by calling

user.has_perm('myapp.create_mymodel')

if you're checking for the create permission for example. Or, like you did, you can use the decorator

permission_required('myapp.create_mymodel')

In addition to the default permissions provided by django, you can define custom permissions on your models by specifying the permissions attribute in the Meta class of your model like this:

class MyModel(models.Model):
    [...]
    class Meta:
        permissions = (
            ("can_deliver_pizzas", "Can deliver pizzas"),
        )

More on defining custom permissions here: https://docs.djangoproject.com/en/dev/ref/models/options/#permissions

By default, permissions can be easily edited for every user using the admin interface. Just visit a certain user's page and there will be a field named User Permissions with a list of all permissions in your project, from which you can add or remove permissions for your particular user.

Upvotes: 5

Related Questions