Last active
June 2, 2025 14:41
-
-
Save benbacardi/227f924ec1d9bedd242b to your computer and use it in GitHub Desktop.
Django reverse with a querystring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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!
That ticket got marked resolved 5 weeks ago. It's not in 5.1, but in the pre-release 5.2 version.
That ticket got marked resolved 5 weeks ago. It's not in 5.1, but in the pre-release 5.2 version.
😮 That's awesome!
dope!
For the record; Django 5.2 was released 2nd April; https://docs.djangoproject.com/en/5.2/releases/5.2/#urls
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!!
Good ol' google search pointed me here :)