Redirection + 403 error

不羁的心 提交于 2019-12-19 22:01:59

问题


I am searching for a way to have something like that :

return HttpResponseForbiddenRedirect(reverse("view_name"))

an HttpResponse which redirect to a view (with its name) but still throw a 403 error

I tried to do something like that :

class HttpResponseForbiddenRedirect(HttpResponse):
    def __init__(self, redirect_to):
        super(HttpResponseForbiddenRedirect, self).__init__()
        self['Location'] = iri_to_uri(redirect_to)
        self.status_code = 403

But it didn't work. For some reason I don't understand, I don't get any content


回答1:


It doesn't work because you can't have a 403 response that is also acted upon as if it is a 302 response.

The HTTP spec tells browsers how to handle certain status codes, and so a browser getting a 403 won't bother to look to see if there's a Location header in the way that it would do with a 302.

If you want to redirect someone from X to Y because they're not allowed to see X, then just issue a standard 302, and do something like setting a message (using django.contrib.messages) to inform the user of why they've been redirected, or redirect them to a page that explains what is going on.




回答2:


You're missing the idea behind HTTP status codes. Redirect is being made with HTTP code 301/302. So you cannot make redirect and return 403 at the same time. It is simply not a redirect, if there is no 301/302 code returned.

I don't get it why you need this, but you can always make a view like:

def my403view(request): # e.g. /403.html
    return HttpResponseForbidden()

and to do your redirect with:

return HttpResponseRedirect(reverse("403.html"))

This will redirect(with code 302) to "my403view", and it will return 403.




回答3:


I found a solution to this :

from app_name.views import my_view

....
    retour = my_views(request)
    return HttpResponseForbidden(retour)

It is in fact quite simple

And so I get the 403 error + the page I wanna load



来源:https://stackoverflow.com/questions/11324909/redirection-403-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!