Django redirect using reverse() to a URL that relies on query strings
Question: I'm writing a django application with a URL like
'http://localhost/entity/id/?overlay=other_id'. Where id is the primary key of
the particular entity and overlay is an optional query parameter for a second
entity to be overlaid in the display. The user can only ever update an entity
when viewing objects through an overlay. When POSTing to /update/id, I want to
redirect back to /entity/id, but I don't want to lose my query parameter
during the redirect, as the change in view would be jarring.

For example, I've got the following in my url.py:

    
    
    ...
    (r'^update/(?P<id>.+)/(?P<overlay_id>.+)/$', 'update'),
    (r'^entity/(?P<id>.+)/$', 'view'),
    ...
    

Because overlay_id is required when updating, it's part of the URL, not a
query parameter. In the django view I want to redirect after a successful POST
and use reverse() to avoid referencing URLs in my python code. The general
idea is:

    
    
    return HttpResponseRedirect(
      reverse('views.view',
        kwargs={
          'id': id,
        },
      )
    )
    

But how do I pass my query parameter though reverse?

Thanks, Craig


Answer: You can use a Django QueryDict object:

    
    
    from django.http import QueryDict
    
    # from scratch
    qdict = QueryDict('',mutable=True)
    
    # starting with our existing query params to pass along
    qdict = request.GET.copy()
    
    # put in new values via regular dict
    qdict.update({'foo':'bar'})
    
    # put it together
    full_url = reversed_url + '?' + qdict.urlencode()
    

And of course you could write a convenience method for it similar to the
previous answer.

