allowing only super user login
-
05-07-2019 - |
Question
I have written a django page that requires only super users to login. So I have added
foo_view = staff_member_required(foo_view)
but it doesn't cut, now I can control only allowing staff marked users to login but this doesn't cut. I have tried something like
def foo_view(request):
if not request.user.is_superuser:
#render some "not allowed page"
#else render the page
but it doesn't seem to help as giving me errors.
Solution
Try:
from django.contrib.auth.decorators import user_passes_test
def foo_view(request):
# ...
foo_view = user_passes_test(lambda u: u.is_superuser)(foo_view)
Or (with Python >= 2.4):
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.is_superuser)
def foo_view(request):
# ...
OTHER TIPS
The code you suggested works perfect for me, I used it in many projects since Django 1.4:
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
@login_required
def foo_view(request):
if not request.user.is_superuser:
return HttpResponse('The user is not superuser')
# Do whatever you need to do
This code works perfect for me since Django 1.4 to 1.7 at least.
Above answers seems to be for very early versions of django. They are bit complicated than for the more later version
for django 1.11 here is a bit similar but simpler strategy. click here
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow