Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set user permissions for specific views in Django

I am using Django to make a website with a bunch of different pages. I only have views, I have not defined any models in my project. I want certain users to have restricted access (they can only see some of the views I've created). I've set up some users in the Django admin site and added login functionality to my website using the Python @login_required decorator.

I'm a little lost on how to set viewing permissions for each user though. I've looked at the @permission_required decorator but it seems to only pertain to models and not views. How do you set page viewing permissions in Django?

like image 990
kdubs Avatar asked Oct 12 '15 17:10

kdubs


3 Answers

Permissions are linked to models. If your authorization logic is linked to the view and not to a model, consider creating a group and using the user_passes_test decorator. For example, lets say you have a report that only supervisors can see: create a group named Supervisors and test for membership:

def must_be_supervisor(user):
    return user.groups.filter(name='Supervisors').count()

@user_passes_test(must_be_supervisor)
def quarter_report(request):
    ...
like image 89
Paulo Scardine Avatar answered Oct 18 '22 22:10

Paulo Scardine


You should use user_passes_test decorator for views. Django documentation has a nice example of it's usage https://docs.djangoproject.com/en/1.8/topics/auth/default/#django.contrib.auth.decorators.user_passes_test

Edited: actually you can use permission_required decorator for views also https://docs.djangoproject.com/en/1.8/topics/auth/default/#django.contrib.auth.decorators.permission_required

like image 34
Nick Avatar answered Oct 19 '22 00:10

Nick


Take a look at django-braces. It's a superb app for exactly this purpose; https://django-braces.readthedocs.org/en/latest/index.html

It provides a mixin for almost every eventuality for use in views & forms which allow you to perform checks to restrict access how you see fit.

like image 1
markwalker_ Avatar answered Oct 19 '22 00:10

markwalker_