user3854113
user3854113

Reputation:

Django import variables from file

I want to create a new .py file where I want to store some specific variables that are going to change continuously

For example in a variables.py

var1 = 5
var2 = 10
var3 = "Hello"

And then in the views.py just do from myapp.variables import * And I want to use them in all the views only rendering

{{ var1 }}
{{ var2 }}

Why it doesnt work ?

Upvotes: 0

Views: 1919

Answers (2)

Stuart Leigh
Stuart Leigh

Reputation: 856

If they aren't being used by the views, but only for the rendering you could make a context_processor

inside your_app/variables.py

def my_variables(request):
    return {
        "var1": True,
        "var2": "foo",
        "var3": 42,
    }

then in your settings.py set

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "your_app.variables.my_variables",
)

These variables will now be available in every template that you render.

Upvotes: 2

agconti
agconti

Reputation: 18093

You just need to pass them in as context:

from django.shortcuts import render
from myapp.variables import var1, var2, var3

def my_view(request):
    return render(request, 'myapp/index.html', {"var1":var1, "var2":var2, "var3":var3})

https://docs.djangoproject.com/en/1.6/topics/http/shortcuts/

Upvotes: 0

Related Questions