【问题标题】:How to access constants in models.py, from django template?如何从 django 模板访问 models.py 中的常量?
【发布时间】:2016-07-20 07:51:25
【问题描述】:

我想在我的网站上显示大约 10 个常量。这些常量在 models.py 中指定。

如何在我的 Django 模板中使用这些常量?

我正在使用基于类的视图。

class PanelView(RequireBuyerOrSellerMixin, TemplateView):
    template_name = "core/panel.html"

【问题讨论】:

    标签: django django-models django-templates


    【解决方案1】:

    您应该在 view.py 中导入它们,然后在您的视图函数中,将它们传递到上下文中以提供模板。

    models.py

    CONSTANT1 = 1
    CONSTANT2 = 2
    

    view.py

    from app.models import CONSTANCT1, CONSTANCE2
    
    def func(request):
        context['constant1'] = CONSTANT1
        context['constant2'] = CONSTANT2
        # return HttpResponse()
    

    模板.html

    {{ constant1 }}
    {{ constant2 }}
    

    编辑:

    基于类的视图与基于函数的视图没有区别。根据django docs,覆盖get_context_data 以在上下文中添加额外的内容。

    【讨论】:

    • 谢谢我正在使用基于类的视图
    • 导入的常量名称和声明的常量变量名称存在细微差异;)
    【解决方案2】:

    通常您应该按照@Shang Wang 建议的方式进行,但是如果您想在许多模板中使用常量,可能值得写一个custom template tag

    from django import template
    from app import models
    
    register = template.Library()
    
    @register.simple_tag
    def get_constants(name):
        return getattr(models, name, None)
    

    在你的模板中:

    {% get_constants 'CONSTANT1' %}
    

    【讨论】:

    • 如果是字典可以访问吗?
    • 在 django1.9 中,您可以将其保存在模板变量中,然后访问 dict 的值。
    猜你喜欢
    • 2020-09-11
    • 2012-09-27
    • 2023-03-04
    • 2011-02-02
    • 1970-01-01
    相关资源
    最近更新 更多