hello I would like to know if we can make a page accessible only to administrators (superuser) I can find nothing in the documentation but I would like my analysis page to be accessible only by superuser without using a boolean in the profile
Asked
Active
Viewed 188 times
2 Answers
1
You can decorate the view with the @staff_member_required
decorator [Django-doc], for example:
# app/views.py
from django.contrib.admin.views.decorators import staff_member_required
@staff_member_required
def my_view(request):
# …
or for class-based views (CBVs), you can make use of a UserPassesTestMixin
mixin [Django-doc]:
# app/views.py
from django.contrib.auth.mixins import UserPassesTestMixin
class StaffMemberRequiredMixin(UserPassesTestMixin):
def test_func(self):
return self.request.user.is_staff
class MyView(StaffMemberRequiredMixin, View):
# …

Willem Van Onsem
- 443,496
- 30
- 428
- 555
0
my_html_page
{% if request.user.is_superuser %}
so your html tags and other data you want to show
{% else %}
you're not authorized to see the content
{% end %}
or also you are able to do such restrictions in the views.py:
def view_p(request):
if not request.user.is_superuser:
return HttpResponseBadRequest()
it would be better idea to create a decorator or use an existing one, if you want to do this restriction alot, and another good idea is instead of Http-bad-request, send a better message to the user to explain the reason of considering his/her request as bad.( may return a html page that has the message) also see this: Django: Hide button in template, if user is not super-user

Community
- 1
- 1

mh-firouzjah
- 834
- 1
- 6
- 15
-
thanks willem and mahdi – moh Feb 20 '20 at 22:32