Django使用reverse()重定向到依赖于查询字符串的URL

Cra*_*ard 13 django django-views

我正在编写一个django应用程序,其URL为'http:// localhost/entity/id /?overlay = other_id'.其中id是特定实体的主键,而overlay是第二个实体在显示中重叠的可选查询参数.用户只能在通过叠加层查看对象时更新实体.当POST到/ update/id时,我想重定向回/ entity/id,但我不希望在重定向期间丢失我的查询参数,因为视图中的更改会变得不和谐.

例如,我在url.py中有以下内容:

...
(r'^update/(?P<id>.+)/(?P<overlay_id>.+)/$', 'update'),
(r'^entity/(?P<id>.+)/$', 'view'),
...
Run Code Online (Sandbox Code Playgroud)

因为更新时需要overlay_id,所以它是URL的一部分,而不是查询参数.在django视图中,我想在POST成功后重定向并使用reverse()来避免在我的python代码中引用URL.一般的想法是:

return HttpResponseRedirect(
  reverse('views.view',
    kwargs={
      'id': id,
    },
  )
)
Run Code Online (Sandbox Code Playgroud)

但是如何通过反向传递我的查询参数?

谢谢,克雷格

小智 22

您可以使用Django QueryDict对象:

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()
Run Code Online (Sandbox Code Playgroud)

当然,您可以为它编写一个类似于上一个答案的便捷方法.


ist*_*ble 6

你不能只检查一下overlay_id并将其添加到你的网址吗?

redirect_url = reverse( ... )
extra_params = '?overlay=%s' % overlay_id if overlay_id else ''
full_redirect_url = '%s%s' % (redirect_url, extra_params)
return HttpResponseRedirect( full_redirect_url )
Run Code Online (Sandbox Code Playgroud)