开发者

How do I redirect users who try to access admin area in Django?

开发者 https://www.devze.com 2023-04-04 11:20 出处:网络
I\'ve noticed an interesting problem with Dj开发者_C百科ango\'s admin area. If I revoke my staff permissions and try to access /admin directly, I would normally expect a redirect to my login page with

I've noticed an interesting problem with Dj开发者_C百科ango's admin area. If I revoke my staff permissions and try to access /admin directly, I would normally expect a redirect to my login page with /admin/ in the query string as a future redirect. However, I get a proper page returned with HTTP code 200 which actually uses my admin/login.html template to render that requested page instead of redirecting. It seems the problem lies within the @staff_member_required decorator, which admin views obviously use.

The question is: is this done on purpose? If not, how can I change this behaviour without too much monkey-patching?


This is done on purpose, because many people implement redirects in thier sites which could block access to the admin panel. Because the admin panel is it's own app it redirects to itself.

# Put this code somewhere it will be imported REALLY early

from django.contrib.admin.views import decorators

def staff_member_required(view_func):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, displaying the login page if necessary.
    """
    def _checklogin(request, *args, **kwargs):
        if request.user.is_active and request.user.is_staff:
            # The user is valid. Continue to the admin page.
            return view_func(request, *args, **kwargs)
        else:
            return HTTPResponseRedirect('/my/login/page/')
    return wraps(view_func)(_checklogin)

decorators.staff_member_required = staff_member_required #replaces the function in-place
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号