Home > Enterprise >  How can I set that when user is admin only then he can view a specific html page in Django
How can I set that when user is admin only then he can view a specific html page in Django

Time:02-05

I've a html page called admin_dashboard.html. So, there is a button in the navbar called Admin Dashboard only admin can get this button. If admin click this button he will go to the admin_dashboard.html but a staff can also go to that page by using urls which is http://127.0.0.1:8000/admin_dashboard. So I want that a if staff manually types this url and tries to go to the admin_dashboard.html it will throw an error.

here is my code for that button

            {%if user.is_superuser%}
            <li><a  href="admin_dashboard">Admin Dashboard</i></a></li>
            {%endif%}

urls.py:

   path("admin_dashboard", views.admin_dashboard, name='admin_dashboard')

views.py

@login_required(login_url='/login')
def admin_dashboard(request):
    return render(request,'admin_dashboard.html')

CodePudding user response:

You can do it this way :


@login_required(login_url='/login')
def admin_dashboard(request):
    if request.user.is_superuser :  
      return render(request,'admin_dashboard.html')
    else: 
        return render(request,'html_view_with_error',{"error" : "PERMISSION DENIED"})



CodePudding user response:

You can check if it is superuser or not in views.py and render template accordingly as

@login_required(login_url='/login')
def admin_dashboard(request):
    if request.user.is_superuser == True:
        return render(request, 'admin_dashboard.html')
    else:
        # render to any html if it is not `superuser`
        return render(request, 'non_superuser_dashboard.html')
  •  Tags:  
  • Related