首页 > 解决方案 > Django 重定向后两页

问题描述

我有一个装饰器来保护我网站的某些部分。

def admin_only(view):
    @wraps(view)
    def _view(request, *args, **kwargs):
        if not Group.objects.get(name='admin') in request.user.groups.all():
            return redirect('main:unauthorized')
        return view(request, *args, **kwargs)
    return _view

因此,如果用户不在管理员组中,他们将被重定向到呈现“未经授权的等等等等模板”的视图。

我想要做的是将用户重定向回他们尝试访问禁止页面时的位置。然后我会使用类似的东西

if not Group.objects.get(name='admin') in request.user.groups.all():
            messages.error("Unauthorized blah blah blah"
            **redirect to where they were or home incase they used direct link**

标签: djangodjango-modelsdjango-viewsdjango-templates

解决方案


request.META.get('HTTP_REFERER')是用户尝试访问禁止视图时所在的链接

  def admin_only(view):
        @wraps(view)
        def _view(request, *args, **kwargs):
            if not Group.objects.get(name='admin') in request.user.groups.all():
                messages.error(request, "Access Denied")
                return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
            return view(request, *args, **kwargs)
        return _view

你可以关注Reddit上的对话


推荐阅读