【问题标题】:Django include google analytics code only in production but not in developmentDjango 仅在生产中包含谷歌分析代码,但在开发中不包含
【发布时间】:2015-02-09 09:18:39
【问题描述】:

我有一个单独的模板中的谷歌分析代码,所以我可以在任何地方都包含它。

由于我不希望代码在开发中显示,我只是将其包装在 if 模板标签中:

... header of any template
{% include 'analytics.html' %}
</head>
.... rest of page

analytics.html 的内容:

{% if not debug %}
<script>
... analytics code
</script>
{% endif %}

在开发中,它按预期工作,分析代码从未显示。

但是,在生产中,分析代码只出现在主页中,在其他所有页面上它都保持隐藏。

这是我的 urls.py 的摘录(我正在使用 TemplateView):

url(r'^$', TemplateView.as_view(template_name="landing/home.html"), name='home'),
url(r'^prices/', TemplateView.as_view(template_name="landing/prices.html"), name='prices'),
url(r'^addons/', TemplateView.as_view(template_name="landing/addons.html"), name='addons'),

这些模板中的每一个都有{% include 'analytics.html' %},(我没有从一个共同的基础扩展它们,因为它们的设计差异太大)。

和我的模板上下文处理器:

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
    "allauth.account.context_processors.account",
    "allauth.socialaccount.context_processors.socialaccount",
)

我在生产中将DEBUGTEMPLATE_DEBUG 设置为False

我错过了什么?

【问题讨论】:

标签: django django-templates


【解决方案1】:

我认为实现这一点的更好方法是将您的 Google Analytics(分析)属性 ID 放入您的 settings.py 并为其编写自定义上下文处理器。您可以将它包含在您的基本模板中(或在您的情况下包含在每个基本模板中),如下所示:

{% if G_A_PROPERTY_ID %}{% include 'analytics.html' %}{% endif %}

还有你的自定义上下文处理器:

# context_procossor.py
def google_analytics(request):
    g_a_p_id = getattr(settings, 'G_A_PROPERTY_ID', False)
    if g_a_p_id:
        return {
            'G_A_PROPERTY_ID': g_a_p_id,
        }
    return {}

不要忘记将您的自定义 context_processor.py 添加到您的 settings.py 中的 TEMPLATE_CONTEXT_PROCESSORS 中。

在生产服务器上设置 G_A_PROPERTY_ID 在 settings.py 文件中(或者在 local_settings.py 如果你使用它),但不在开发服务器上。这样它应该可以按预期工作。

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多