settings.py 中的乘客 Django 自定义变量未传递给模板

Passenger Django custom variable in settings.py is not passed to template

当我的 Django 应用程序在本地或测试服务器上运行时,我希望 disqus comments 被禁用。

所以在我的 Django settings.py 我正在使用:

DEBUG = True
DISQUS = False

现在在我的 django blog_post.html 模板中我有一个 IF 语句:

{% if DISQUS %}
   <div id="disqus_thread"></div>
    <script>
         etc.
         etc.
    </script>
{% else %}
   <p>Disqus disabled...</p>
{% endif %}

当我将代码推送到实时服务器 (DISQUS = True) 时,评论部分将出现在我的 html 页面中。

当我使用 Apache mod_wsgi 时,我对这个设置没有任何问题!

然而,在切换到 Passenger 后,它就停止工作了。我已经尝试了几乎所有已知的组合,但没有希望。 DISQUS 自定义变量不会传递给模板。

为什么它适用于 mod_wsgi 而不是 mod_passenger?

Apache/2.4.6 (CentOS) Phusion_Passenger/5.0.28

谢谢

愚蠢的我! Daniel 的评论让我重新思考了这个问题。

我什至在 Whosebug 上找到了 a similar 3y old issue and also a better reference in another thread about accessing constants in settings.py from templates in Django,它更好地描述了问题。

从 Django 1.8 开始,事情变得更加简单(您也可以查看 Upgrading templates to Django 1.8)。


我切换到 django 应用程序目录,我在其中创建了文件 context_processors.py

from django.conf import settings

def disqus(context):
  return {'DISQUS': settings.DISQUS}



然后我打开 settings.py,其中定义了 TEMPLATES,并将其添加到 context_processors 列表中:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(os.path.dirname(BASE_DIR), 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'blogengine.context_processors.disqus',  # <--- add this line here

            ],
        },
    },
]


现在我可以在 settings.py 中将 DISQUS 设置为 TrueFalse,html 模板将检查状态并显示或隐藏评论部分。