Skip to main content
 首页 » 编程设计

python之从基于 Django 类的 View 重定向到外部页面

2024年10月25日28lautakyan007

我正在尝试根据请求 header 中的引荐来源网址重定向用户。基本上,如果 referer 是 https://www.google.com , 我想将它们发送到一个页面,而不是我的网站上。否则,照常继续处理。

这是我目前的情况

class ArticleAccess(TemplateView, SomeMixin): 
    http_method_names = ['get'] 
    template_name = 'template.html' 
 
    def dispatch(self, request, *args, **kwargs): 
        return super(ArticleAccess, self).dispatch(request, *args, **kwargs) 
 
    def get_context_data(self, **kwargs): 
 
        context = super(ArticleAccess, self).get_context_data(**kwargs) 
        item = get_object_or_404(ClientItem.objects.using(self.get_site().name), id=kwargs['article_id']) 
 
        if self.request.META.get('HTTP_REFERER') == 'https://www.google.com/': 
            return redirect(item.item_url) 
 
        context['id'] = item.id 
        context['name'] = item.name 
        context['html'] = item.description 
        context['item_url'] = item.item_url 
 
        return context 

这只是停留在同一页面上而不是重定向。我也尝试过 HttpResponseRedirect,但无济于事

请您参考如下方法:

alecxe 是正确的。您必须从预期返回 HttpResponse 的方法重定向。

get_context_data 不应返回 HttpResponse 并且永远不会由 view 返回。它总是用来获取数据字典来填充模板。无论您从此方法返回什么,它都不会覆盖响应。

因此无论你在哪里写这个override,它都需要在一个期望返回响应的地方,比如get, post, dispatch.

现在的问题是确定如何在 get_context_data 方法之外获取对象。