Search code examples
djangomiddleware

Django context processors and URL arguments


I have some code that is repeated at the start of my Django views. It basically just adds some variables to the context, but based on the URL argument, e.g.

def someView(request, id):
   target = Target.objects.get(id=id)
   # name will be added to ctx
   name = target.name

(there are more attributes added and other attributes from related models, but this gives the general idea --- There are quite a few lines of repeat code at the start of each view)

I thought I could make my code more DRY by taking advantage of Django's context processors, but it would seem these don't access to the URL arguments?

Is there another way to avoid these repeat lines? Maybe middleware or something else?


Solution

  • You can access the URL parameters via request through the resolver_match attribute. So for instance you can do request.resolver_match.kwargs['id'] to get the ID kwarg.