如何让Google Tag Manager执行python和Django代码?

问题描述 投票:0回答:1

我正在尝试使用Google跟踪代码管理器(GTM)代码替换Google Analytics(GA)代码。该代码旨在识别我们系统中具有用户名的用户。

在我目前的GA代码中,我通过Django调用一个文件:

    {{ google_analytics }}

这提取了这段代码:

    def google_analytics(request):
disabled = {"google_analytics": ""}

# don't track internal users
if request.user and request.user.is_authenticated:
    if request.user.email and request.user.email.lower().endswith('@trellis.law'):
        return disabled

    if request.user.username in lawbook.config.developers:
        return disabled

    if request.user.username in lawbook.config.blog_writers:
        return disabled

    if request.user.username in lawbook.config.bio_writers:
        return disabled

    if request.user.is_staff or request.user.is_superuser:
        return disabled

# don't track in local development environment
if settings.DEBUG:
    return disabled

# don't track in staging
if lawbook.config.hostname.startswith('staging'):
    return disabled

if request.user and request.user.is_authenticated:
    username = request.user.username
else:
    username = None

context = {
    "google_analytics_key": settings.GOOGLE_ANALYTICS_KEY,
    "username": username
}

return {
    'google_analytics': render_to_string("google_analytics.html", context) 
}

我需要做的就是设置一个标签,在每个页面上执行此操作。我怎么做?

python django google-tag-manager
1个回答
1
投票

不确定一个想法是多么好的公开分享你的密钥,但是,这里是你所要求的django的解决方案。

def google_analytics_context_processor(request):
    # rest of your code
    return {'google_analytics': render_to_string("google_analytics.html", context)}

然后在你的设置中

TEMPLATES = [
    {
        ...,
        'OPTIONS': {
            'context_processors': [
                ...,
                'dot.path.to.google_analytics_context_processor',
            ],
        },
    },
]

然后在您使用的函数视图(基于类的视图自动处理它)中

from django.template.context import RequestContext
def view(request):
    custom_context = {'custom': 'context'}
    context = RequestContext(request, custom_context)
    # now where-ever you want, you use this context 
    # and your context from the context_processors added 
    # in your new context 
© www.soinside.com 2019 - 2024. All rights reserved.