在 RedirectView 中添加自定义 http header

Add custom http header in RedirectView

我想添加 http header 但它不起作用。 我正在尝试使用打印来测试解决问题,但它似乎什么都没有

这是我的代码,但不起作用:

class MyRedirectView(RedirectView):

    def head(self, *args, **kwargs):
        response = HttpResponse()
        response['X-Robots-Tag'] = 'noindex'
        print('TEST')
        return response

您在这里所做的是重写head 方法。仅当向 url 发出 HEAD 类型的 HTTP 请求时才使用它。您应该重写 get 方法,或者更好的是改写 dispatch 方法。

class MyRedirectView(RedirectView):

    def dispatch(self, *args, **kwargs):
        response = super(MyRedirectView,self).dispatch(*args, **kwargs)
        response['X-Robots-Tag'] = 'noindex'
        print('TEST LOL')
        return response