Вы можете попробовать отправить свою переменную в контекст каждого представления, основанного на классе, имея родительский класс и унаследовав все представления от этого.
class MyMixin(object):
def get_context_data(self, **kwargs):
context = super(MyMixin, self).get_context_data(**kwargs)
myvariable = "myvariable"
context['variable'] = myvariable
return context
# then you can inherit any kind of view from this class.
class MyListView(MyMixin, ListView):
def get_context_data(self, **kwargs):
context = super(MyListView, self).get_context_data(**kwargs)
... #additions to context(if any)
return context
Или, если вы используете представления на основе функций, вы можете использовать отдельную функцию, которая может обновлять ваш контекст dict
.
def update_context(context): #you can pass the request object here if you need
myvariable = "myvariable"
context.update({"myvariable": myvariable})
return context
def myrequest(request):
...
context = {
'blah': blah
}
new_context = update_context(context)
return render(request, "app/index.html", new_context)