Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 在模板中使用设置文件中的变量_Django_Django Templates - Fatal编程技术网

Django 在模板中使用设置文件中的变量

Django 在模板中使用设置文件中的变量,django,django-templates,Django,Django Templates,大家好!我想访问我在setting.py文件中声明的常量值,以便在我的模板中使用,但不是在应用程序内的模板中,我只想在我的主模板中使用我在设置文件中声明的模板 CMS_TEMPLATES = ( ## Customize this ('page.html', 'Page'), ('feature.html', 'Page with Feature'), ('homeTemplate.html', 'Home Template') // I want to use

大家好!我想访问我在setting.py文件中声明的常量值,以便在我的模板中使用,但不是在应用程序内的模板中,我只想在我的主模板中使用我在设置文件中声明的模板

CMS_TEMPLATES = (
    ## Customize this
    ('page.html', 'Page'),
    ('feature.html', 'Page with Feature'),
    ('homeTemplate.html', 'Home Template') // I want to use here
)
我在StackOverflow中找到了关于相同问题的示例,但所有案例都在应用程序内部使用变量,而不是在顶层


如何在此模板中使用此值的最佳方法

我首先要问——你为什么要这么做?这似乎是一种奇怪的。。。调整你正在使用的模板目录,我猜

如果你发布了你想要达到的目标,这可能比针对这个问题的具体解决方案要好

大体上,您只能在使用django的项目或脚本中,或者至少在其环境中,为django变量提供服务(包括来自
settings.py
)。从django.conf导入设置执行
导入项目中最高级别的设置,这些设置可跨所有应用程序使用。项目是以这种粗略的方式布置的

myproject - 
    - myapp1 
    - myapp2 
    - myproject 
        - settings.py
        - wsgi.py 
    - manage.py 
与此一样,对于外部脚本,y因此:

但是:这仍然无法将其放入模板中,因为从这里将变量放入模板需要使用django引擎来呈现响应

如果django系统没有为它提供服务,那么它就不是一个模板,它只是一个普通的html文件

如果它是整个项目中另一个应用程序中的模板,您可以将其作为上下文词典的一部分传递

import os
import django
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()
# now you can use settings.VARIABLE_NAME