In Django, How Do I Restrict Is_staff Member To Access A Url?
Solution 1:
If you want to use a decorator, you can use the user_passes_test
. First define a test function that checks that the user is not a staff member.
defis_not_staff(user):
returnnot user.is_staff
You can change the function to check user.is_authenticated
(user.is_authenticated()
in Django <=1.9) as well, if you don't want anonymous users to be able to access the view.
Then use user_passes_test
with your test function to decorate the view you wish to protect.
@user_passes_test(is_not_staff)defnon_staff_view(request):
...
Solution 2:
You can simply inherit LoginRequiredMixin
and create your own custom access mixin as below:
classAccessMixin(LoginRequiredMixin):defdispatch(self, request, *args, **kwargs):
ifnot request.user.is_authenticated or request.user.is_staff:returnself.handle_no_permission()
returnsuper().dispatch(request, *args, **kwargs)
Now you just need to inherit AccessMixin
in your view as below:
classHomePageView(AccessMixin, TemplateView):
login_url = <login-url>
...
...
So anonymous user and staff user won't be able to access the content of the page.
You can also mention the same in your base template html
Consider you have created a base.html
which extends content
block and you can add permission as below:
Ex.
base.html
{% if user.is_authenticated %}
{% if user.is_staff %}
<h3>Not allowed to access this page</h3>
{% else %}
{% block content %} {% endblock %}
{% endif %}
{% endif %}
this way when you extend base.html in your template all the content you write within {% block content %} {% endblock %}
will only be rendered for non-staff logged in user.
Post a Comment for "In Django, How Do I Restrict Is_staff Member To Access A Url?"