Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 do I use these constants in my Django template?

I'm using class-based views.

class PanelView(RequireBuyerOrSellerMixin, TemplateView):
    template_name = "core/panel.html"
like image 727
User Avatar asked Mar 31 '16 18:03

User


2 Answers

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.

like image 119
Shang Wang Avatar answered Oct 08 '22 19:10

Shang Wang


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' %}
like image 45
ilse2005 Avatar answered Oct 08 '22 17:10

ilse2005