Skip to content

Instantly share code, notes, and snippets.

@benbacardi
Last active February 13, 2024 20:53
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save benbacardi/227f924ec1d9bedd242b to your computer and use it in GitHub Desktop.
Save benbacardi/227f924ec1d9bedd242b to your computer and use it in GitHub Desktop.
Django reverse with a querystring
from django.utils.http import urlencode
def reverse_querystring(view, urlconf=None, args=None, kwargs=None, current_app=None, query_kwargs=None):
'''Custom reverse to handle query strings.
Usage:
reverse('app.views.my_view', kwargs={'pk': 123}, query_kwargs={'search': 'Bob'})
'''
base_url = reverse(view, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app)
if query_kwargs:
return '{}?{}'.format(base_url, urlencode(query_kwargs))
return base_url
@rafagarciac
Copy link

rafagarciac commented May 22, 2020

Hi ! Great solution ! 👍
query_kwargs={'search', 'Bob'} should be query_kwargs={'search': 'Bob'}
For the other hand, you missed a parenthesis in: '{}?{}'.format(base_url, urlencode(query_kwargs))

Otherwise you'll get a unpack error in urlencode() method.

@benbacardi
Copy link
Author

Good spot! Fixed.

How on earth did you come across this snippet anyway!?

@daveboling
Copy link

daveboling commented Jun 5, 2020

Came across this while Googling for 'django url reverse with query string'. I don't think https://code.djangoproject.com/ticket/25582 will be a core enhancement anytime soon. Great solution!

@tomwojcik
Copy link

Ditto. I can't believe it's not available yet. Thanks Ben!

@GrazingScientist
Copy link

This is a neat function. Thanks @benbacardi . Under what license do you provide this gist? Could you please add it, so we can reuse it?

@benbacardi
Copy link
Author

@GrazingScientist take it and use it as you wish, no attribution required! It's a simple snippet :)

@landonhughes
Copy link

Thanks!!

Good ol' google search pointed me here :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment