栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

可以从Django中的模板访问settings.py中的常量吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

可以从Django中的模板访问settings.py中的常量吗?

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

from django.shortcuts import render_to_responsefrom django.template import RequestContextfrom django.views.generic.simple import direct_to_templatedef 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 settingsfrom django.shortcuts import render_to_responsedef 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 }}



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380177.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号