I have about 10 constants that I want to display on my website. These constants are specified in models.py.
How do I use these constants in my Django template?
I'm using class-based views.
class PanelView(RequireBuyerOrSellerMixin, TemplateView):
template_name = "core/panel.html"
You should import them in view.py, then in your view function, pass them in the context to feed 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 has no difference than function based views. According to django docs, override get_context_data
to add extra stuff to context.
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
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' %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With