如何让Google标记管理器执行python和Django代码?
我试图用谷歌标签管理器(GTM)代码替换谷歌分析(GA)代码。该代码用于在我们的系统中识别具有用户名的用户 在我当前的GA代码中,我通过Django调用一个文件:如何让Google标记管理器执行python和Django代码?,python,django,google-tag-manager,Python,Django,Google Tag Manager,我试图用谷歌标签管理器(GTM)代码替换谷歌分析(GA)代码。该代码用于在我们的系统中识别具有用户名的用户 在我当前的GA代码中,我通过Django调用一个文件: {{ google_analytics }} 这就产生了这个代码: def google_analytics(request): disabled = {"google_analytics": ""} # don't track internal users if request.user and request.
{{ 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)
}
我需要做的就是在每一页上设置一个标签。如何做到这一点?不知道公开共享密钥有多好,但这里是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