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?
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):
...
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With