Django 使用 reverse() 重定向到依赖查询字符串的 URL [英] Django redirect using reverse() to a URL that relies on query strings
问题描述
我正在编写一个 django 应用程序,其 URL 类似于http://localhost/entity/id/?overlay=other_id".其中 id 是特定实体的主键,overlay 是要在显示中叠加的第二个实体的可选查询参数.用户只能在通过叠加层查看对象时更新实体.当 POST 到/update/id 时,我想重定向回/entity/id,但我不想在重定向过程中丢失我的查询参数,因为视图的变化会很刺耳.
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.
例如,我的 url.py 中有以下内容:
For example, I've got the following in my url.py:
...
(r'^update/(?P<id>.+)/(?P<overlay_id>.+)/$', 'update'),
(r'^entity/(?P<id>.+)/$', 'view'),
...
因为更新时需要overlay_id,所以它是URL的一部分,而不是查询参数.在 Django 视图中,我想在成功 POST 后重定向并使用 reverse() 以避免在我的 python 代码中引用 URL.总体思路是:
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?
谢谢,克雷格
推荐答案
您不能只检查 overlay_id
并将其添加到您的 url 吗?
Can't you just check for an overlay_id
and add it to your url?
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 )
这篇关于Django 使用 reverse() 重定向到依赖查询字符串的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!