1

I have a view in my django backend which I want only admin to see.

@api_view(('GET',))
def get_analytics(request):
# Number of users who dogged in once to our system today
login_count= User.objects.filter(last_login__startswith=timezone.now().date()).count()


data = {}
data['login_count'] = login_count

return JSONResponse(data)

It's a function based view. How can I make it visible only to admin? it's corresponding url I hit from my angular app to get and render the data.

2 Answers 2

2

You can also use the below decorator

from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required
Sign up to request clarification or add additional context in comments.

Comments

2

You can add IsAdminUser permission class to your view to restrict access to only admin users. Only users with admin permissions will be granted access then. Others will be denied access.

@api_view(('GET',))
@permission_classes((IsAdminUser, )) # add the permission class
def get_analytics(request):
    ...
    return JSONResponse(data)

When the permissions fail, then either an exceptions.PermissionDenied or exceptions.NotAuthenticated exception will be raised depending on some conditions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.