How to access constants in models.py, from django template?

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

How to use these constants in my Django template?

I use class based views.

class PanelView(RequireBuyerOrSellerMixin, TemplateView):
    template_name = "core/panel.html"
+4
source share
2 answers

You must import them into view.py, then in your view function, pass them in context to submit the template.

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 are no different than function based views. According to django docs , override get_context_datato add additional material to the context.

+5

@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)

:

{% get_constants 'CONSTANT1' %}
+2

All Articles