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

3

5

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).

Aristides answered 4/2, 2010 at 1:47 Comment(0)
Q
11

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]
Quartering answered 4/2, 2010 at 1:53 Comment(1)
I need to access the view before process_view is called, because I need to stop processing other middlewares in the chain given some condition that depends on a flag stored in the view. Is this possible?Tatyanatau
U
1

If you want to read GET parameters from URL you can use request.GET dictionary:

class MyMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print(request.GET)  # immutable QueryDict
Unaccomplished answered 25/8, 2023 at 12:24 Comment(0)
R
0

You can access URL parameters in the middleware's __call__, process_request or process_response methods by using resolve() like this:

from django.urls import resolve

class MyMiddleware:
  def __init__(self, get_response):
    self.get_response = get_response

  def __call__(self, request):
    match = resolve(request.path_info)
    arg1, arg2 = match.args[:2]

    # do something with arg1, arg2

    return self.get_response(request)
Raye answered 29/11, 2022 at 8:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.