Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Middleware: How do I access a view's params from middleware

Let's say I have a view:

def pony_view(request, arg1, arg2):
    ... Make ponies, etc ...

And a middleware:

class MyMiddleware(object):
    def process_request(request):
        # How do I access arg1, arg2 here?

Of course arg1, and arg2 will be passed in via URL params with urls.py.

The reason I need to do this is because I want to add something to request.session before the view function runs (something that I need from the URL though).

like image 212
orokusaki Avatar asked Dec 23 '22 05:12

orokusaki


1 Answers

You will have to implement the process_view method.

It has this signature:

process_view(self, request, view_func, view_args, view_kwargs)

and is executed before the view function is called:

process_view() is called just before Django calls the view. It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. Response middleware is always called on every response.

Then you should be able to access arg1 and arg2 with:

class MyMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        arg1, arg2 = view_args[:2]
like image 86
Felix Kling Avatar answered Dec 28 '22 13:12

Felix Kling