6

is there anyway to define middleware for specific route or route groups in django? like laravel which we can define it as follows:

Route::get('admin/profile', function () {})->middleware('auth');

unbl0ck3r
  • 371
  • 4
  • 16

1 Answers1

8

Historically there have been a few hooks you can exploit to do something like this. But nowadays you can for sure override:

def process_view(self, request, view_func, view_args, view_kwargs):
     ...

in your middleware class and then you could resolve the view/route from request.path and dispatch custom logic if it matches or not, or you could match over view_func.__name__ or something similar, etc. Depends on your needs.

https://docs.djangoproject.com/en/2.0/topics/http/middleware/#process-view

vishes_shell
  • 22,409
  • 6
  • 71
  • 81
jhrr
  • 1,624
  • 14
  • 22