Home > Net >  How to restrict regular users from accessing admin page?
How to restrict regular users from accessing admin page?

Time:07-28

I would like to allow only admin users to access admin page and raise 404 error if user is not authenticated or is not a staff member. Is there a way to wrap admin view with another function to check if user is admin?

Edit: Uhh, I should have pointed out first that by admin view I mean built-in django admin view. Any user can visit it and there they will see a login page for admins. I would like to override this behavior and raise 404 error, so that only admins are aware of this view. Also I have a login page for everyone, so there's no need for authorization in admin view

CodePudding user response:

Try to wrap your dispatch method on admin view like this:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test

@method_decorator(user_passes_test(lambda u: u.is_authenticated and u.is_staff))
    def dispatch(self, request, *args, **kwargs):  # noqa: D102
        return super().dispatch(request, *args, **kwargs)

If you need this for multiple views, write mixin that overrides dispatch method.

CodePudding user response:

so if you want easy solution just add to your main urls.py above admin urls:

path('admin/login/', view404), #asaing view that return 404
path('admin/', admin.site.urls),
  • Related