user2194805
user2194805

Reputation: 1369

django variable available to all the views

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

.

Upvotes: 4

Views: 2458

Answers (2)

AbrahamCoding
AbrahamCoding

Reputation: 830

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.

Upvotes: 3

Aman Garg
Aman Garg

Reputation: 2547

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)

Upvotes: 1

Related Questions