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

时间:2021-05-15 07:34:23

I have about 10 constants that I want to display on my website. These constants are specified in models.py.

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

How do I use these constants in my Django template?

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

I'm using class-based views.

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

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

2 个解决方案

#1


7  

You should import them in view.py, then in your view function, pass them in the context to feed the template.

您应该在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()

template.html

{{ constant1 }}
{{ constant2 }}

Edit:

Class based views has no difference than function based views. According to django docs, override get_context_data to add extra stuff to context.

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

#2


2  

Usually you should go the way @Shang Wang suggested, but if you want to use the constants in many templates it might be worth to write a custom template tag

通常你应该采用@Shang Wang建议的方式,但如果你想在许多模板中使用常量,那么编写自定义模板标签可能是值得的。

from django import template
from app import models

register = template.Library()

@register.simple_tag
def get_constants(name):
    return getattr(models, name, None)

And in your template:

在您的模板中:

{% get_constants 'CONSTANT1' %}

#1


7  

You should import them in view.py, then in your view function, pass them in the context to feed the template.

您应该在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()

template.html

{{ constant1 }}
{{ constant2 }}

Edit:

Class based views has no difference than function based views. According to django docs, override get_context_data to add extra stuff to context.

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

#2


2  

Usually you should go the way @Shang Wang suggested, but if you want to use the constants in many templates it might be worth to write a custom template tag

通常你应该采用@Shang Wang建议的方式,但如果你想在许多模板中使用常量,那么编写自定义模板标签可能是值得的。

from django import template
from app import models

register = template.Library()

@register.simple_tag
def get_constants(name):
    return getattr(models, name, None)

And in your template:

在您的模板中:

{% get_constants 'CONSTANT1' %}