Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access constants in settings.py from templates in Django?

I have some stuff in settings.py that I'd like to be able to access from a template, but I can't figure out how to do it. I already tried

{{CONSTANT_NAME}} 

but that doesn't seem to work. Is this possible?

like image 249
Paul Wicks Avatar asked Jan 11 '09 16:01

Paul Wicks


People also ask

How do you pass variables from Django view to a template?

And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file. We won't go into a database example for this one.

How do you set constants in Django?

To create a constant in Django. Open your settings.py file and add a variable like MY_CONST = “MY_VALUE”.

What will be the type of templates variable in Django settings file?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.


1 Answers

If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

Here's how:

  1. Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context:

    from django.conf import settings # import the settings file  def admin_media(request):     # return the value you want as a dictionnary. you may add multiple values in there.     return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX} 
  2. add your context processor to your settings.py file:

    TEMPLATES = [{     # whatever comes before     'OPTIONS': {         'context_processors': [             # whatever comes before             "your_app.context_processors.admin_media",         ],     } }] 
  3. Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically:

    from django.shortcuts import render  def my_view(request):     return render(request, "index.html") 
  4. and finally, in your template:

    ... <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a> ... 
like image 76
bchhun Avatar answered Oct 16 '22 20:10

bchhun