程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了可以从Django中的模板访问settings.py中的常量吗?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决可以从Django中的模板访问setTings.py中的常量吗??

开发过程中遇到可以从Django中的模板访问setTings.py中的常量吗?的问题如何解决?下面主要结合日常开发的经验,给出你关于可以从Django中的模板访问setTings.py中的常量吗?的解决方法建议,希望对你解决可以从Django中的模板访问setTings.py中的常量吗?有所启发或帮助;

setTings.MEDIA_URL如果你使用django的内置通用视图或在render_to_response快捷方式函数中传递上下文实例关键字参数,则Django提供对模板的某些经常使用的设置常量的访问,例如和某些语言设置。这是每种情况的示例:

from django.shortcuts import render_to_response
from django.template import requestContext
from django.vIEws.generic.simple import direct_to_template

def my_generic_vIEw(request, template='my_template.HTML'):
    return direct_to_template(request, templatE)

def more_custom_vIEw(request, template='my_template.HTML'):
    return render_to_response(template, {}, context_instance=requestContext(request))

这些视图都将具有几个常用设置,例如setTings.MEDIA_URL可用于模板{{ MEDIA_URL }}等。

如果要在设置中寻找对其他常量的访问权限,则只需解压缩所需的常量并将它们添加到在视图函数中使用的上下文字典中,如下所示:

from django.conf import setTings
from django.shortcuts import render_to_response

def my_vIEw_function(request, template='my_template.HTML'):
    context = {'favorite_color': setTings.FAVORITE_color}
    return render_to_response(template, context)

现在,你可以通过访问setTings.FAVORITE_color模板{{ favorite_color }}

我发现最简单的方法是单个自定义模板标签:

from django import template
from django.conf import setTings

register = template.library()

# setTings value
@register.simple_tag
def setTings_value(Name):
    return getattr(setTings, name, "")

用法:

{% setTings_value "LANGUAGE_CODE" %}

如果你希望每个请求和模板都具有此值,则使用上下文处理器更为合适。

就是这样:

  1. context_processors.py你的应用目录中创建文件。假设我想admin_PREFIX_VALUE在每种情况下都具有价值:
from django.conf import setTings # import the setTings file

def admin_media(request):
    # return the value you want as a Dictionnary. you may add multiple values in there.
    return {'admin_MEDIA_URL': setTings.admin_MEDIA_PREFIX}
  1. 将上下文处理器添加到setTings.py文件中:
TEMPLATES = [{
    # whatever comes before
    'OPTIONS': {
        'context_processors': [
            # whatever comes before
            "your_app.context_processors.admin_media",
        ],
    }
}]
  1. requestContext在视图中使用可以在模板中添加上下文处理器。该render快捷方式自动执行此操作:
from django.shortcuts import render

def my_vIEw(request):
    return render(request, "index.HTML")
  1. 最后,在你的模板中:
...
<a href="{{ admin_MEDIA_URL }}">path to admin media</a>
...

解决方法

我希望通过模板访问setTings.py中的一些内容,但是我不知道该怎么做。我已经试过了

{{CONSTANt_name}}

但这似乎不起作用。可能吗?

大佬总结

以上是大佬教程为你收集整理的可以从Django中的模板访问settings.py中的常量吗?全部内容,希望文章能够帮你解决可以从Django中的模板访问settings.py中的常量吗?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。