简体   繁体   中英

How to insert app-level constants into a django template

Suppose I have a constant defined in my models.py as NUM_IMAGES and I want to access that in a template within the same app. How would I go about doing this? I certainly don't want to put it in the project's settings.py , exposing it to the entire project, nor do I particularly want to expose all settings values to the app as this might hurt modularity. So then, how would I go about referencing my NUM_IMAGES in a template, say detail.html ?

You can easily expose your constants to view by just wrapping them in context. so if you want to access NUM_IMAGES in view first import it into views.py file

from models import NUM_IMAGES

then pass it to required view

def myview(request):
    #something to do
    return render( request,'app/page.html',{'NUM_IMAGES':NUM_IMAGES})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM