Home > front end >  Is there a way to add context to Django reverse function?
Is there a way to add context to Django reverse function?

Time:02-04

Is it possible to pass context through the reverse function in Django in some way like reverse('foo', context={'bar':'baz'})? Or is there a better workaround?

CodePudding user response:

As already described by Sir WillemVanOnsem in the above comment.

You can't provide context in reverse as it only produces a string: a path, eventually it goes to view.

reverse() can only take args and kwargs, see Reversing namespaced URLs for more detail.

CodePudding user response:

Reverse generates an URL. The URL can parse or supply extra context. In urls.py,

path( 'action/<str:context>/', MyView.as_view(), name='foo' )

then

reverse('app:foo', kwargs={'context':'bar:baz quux:help'} )

will generate the URL ending

.../appname/action/bar:baz quux:help

and your view will parse context:

context = self.kwargs.get( context, '')
context_dir = {}
for kv in context.split(' '):
   keyval = kv.split(':')
   context_dir[ keyval[0].strip() ] = keyval[1].strip()

or something like this, ending with context_dir as {'bar':'baz', 'quux':'help'}

Alternatively you can append a querystring to the URL returned by reverse and retrieve that in the view you redirect to via request.GET

url = reverse('foo')   '?bar=baz&quux=help'

redirect, and then in that view request.GET.get('bar') will return "baz" etc.

Finally you can stuff an almost arbitrarily complex context into the user's session (which gets stored either as a cookie in his browser, or an object in your database). This is the most general but also the most complex. See the doc for using Django sessions

  • Related