【问题标题】:Is there a way to preserve the original HTTP_REFERER when using Django's redirect?使用 Django 的重定向时,有没有办法保留原始的 HTTP_REFERER?
【发布时间】:2021-05-08 18:32:18
【问题描述】:

我有一个 Django 网站,我正在使用 Google Analytics 来跟踪我的流量来自哪里。

我想根据用户是否登录或做过其他事情将流量路由到不同的地方。所以在我的views.py中,我有这样一个函数:

def toDefaultLandingPage(request):
    # tell me who the referrer is
    # this is what I want to pass along in the request if I can
    print(request.META.get('HTTP_REFERER'))
    if request.user.is_authenticated:
        try:
            configuration = UserData.objects.get(user=request.user)
            return redirect('/home/')
        except:
            # user has not configured their profile yet
            return redirect('/user/')
    else:
        # promo page for non-logged in users
        return redirect('/about/')

这很好用,只是 Google Analytics(分析)说我的大部分流量都没有引荐来源网址。我知道这是一个谎言,因为默认登录页面中的打印语句大约有 70% 的时间包含 google 或 facebook。

有什么方法可以将原始引荐来源网址传递给我使用的 3 个不同的重定向?

【问题讨论】:

    标签: django http-headers


    【解决方案1】:

    我很想知道对此的“正确”解决方案是什么。我通过直接调用视图来解决这个问题:

    我没有调用return redirect('/home/'),而是调用了return home(request),其中home 是一个普通函数:

    def home(request):
        context = {
            'rewrite_url': '/home/',
        }
    return render(request,'some_template.html', context=context)
    

    这种方法的问题是 URL 没有更新。所以,我在some_template.html 中使用了一些javascript 来改变它:

    {% if rewrite_url %}
      <script>
      window.onload = function() {
        history.pushState("{{ rewrite_url }}", "", "{{ rewrite_url }}");
      }
      </script>
    {% endif %}
    

    再一次,这似乎有点骇人听闻,我希望有一个更清洁的解决方案。

    【讨论】:

      猜你喜欢
      • 2021-01-09
      • 1970-01-01
      • 2013-09-05
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 2015-01-03
      • 2017-04-06
      相关资源
      最近更新 更多