4

With context_processors it' s easy to define a callable which results variables available to all the templates. Is there any similar technique which makes a variable available to all the views? Is that somehow possible? Maybe with some workaround?

Django: 2.2 Python: 3.5.3

.

user2194805
  • 1,201
  • 1
  • 17
  • 35

2 Answers2

3

You may want to implement a custom Middleware.

https://docs.djangoproject.com/en/dev/topics/http/middleware/

This lets you execute custom code for every request and attach the results to the request object, which is then accessible in your view.

AbrahamCoding
  • 780
  • 9
  • 13
1

You can try sending your variable to the context of each class based view by having a parent class and inheriting all the views from that.

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

Or if you are using function based views, you can use a separate function which can update your 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)
Aman Garg
  • 2,507
  • 1
  • 11
  • 21