Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a value to every view with django middleware

I have a middleware function that overrides process view.

I want to pass a variable to every view. Is the best place to do this in the request, args or kwargs parameter to view_func?

I tried this with no luck:

def process_view(self, request, view_func, view_args, view_kwargs):
        view_kwargs['value'] = 'my value'

        response = view_func(request, *view_args, **view_kwargs)


        return response

How can I pass a value to every view with middleware?

like image 522
Atma Avatar asked Dec 12 '25 17:12

Atma


1 Answers

Bars on your comment, you probably want to use a context processor to get your variable into the template context.

Edit for example

It's pretty trivial, but here you go:

def my_context_processor(request):
    if request.session['my_variable']:
        return {'foo': 'bar'}

then you add myapp.mymodule.my_context_processor to TEMPLATE_CONTEXT_PROCESSORS in settings.py, and make sure you use the render shortcut in the view to render your template.

like image 163
Daniel Roseman Avatar answered Dec 15 '25 16:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!