gpt4 book ai didi

django - 如何从 Django 模板访问 models.py 中的常量?

转载 作者:行者123 更新时间:2023-12-04 14:10:27 24 4
gpt4 key购买 nike

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

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

我正在使用基于类的 View 。

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

最佳答案

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

模型.py

CONSTANT1 = 1
CONSTANT2 = 2

查看.py
from app.models import CONSTANCT1, CONSTANCE2

def func(request):
context['constant1'] = CONSTANT1
context['constant2'] = CONSTANT2
# return HttpResponse()

模板.html
{{ constant1 }}
{{ constant2 }}

编辑:

基于类的 View 与基于函数的 View 没有区别。根据 django docs , 覆盖 get_context_data在上下文中添加额外的东西。

关于django - 如何从 Django 模板访问 models.py 中的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36340525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com