3

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?

Atma
  • 29,141
  • 56
  • 198
  • 299
  • If a user has not set a setting, I want to popup a message to them. I will base this off of a session variable. I figured if the session variable was true, I would pass a variable to the view to pass to the template. Is there a better way? – Atma Aug 19 '13 at 21:41

1 Answers1

7

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    should I still be using the middleware override in conjunction with the context processor? – Atma Aug 19 '13 at 22:31
  • 1
    No, why would you need to? You have access to the request, and therefore the session, directly in the context processor, so all the logic can go there. – Daniel Roseman Aug 19 '13 at 22:40
  • 1
    can you show an example? I can't find any example of the request context being able to pass variable to a template based on conditional logic. Thanks a million. – Atma Aug 19 '13 at 23:05