Django使用reverse()重定向到依赖于查询字符串的URL [英] Django redirect using reverse() to a URL that relies on query strings
问题描述
例如,我的url.py中有以下内容:
...
(r'^ update /(?P< id>。+)/(?P< overlay_id> +)/ $','update' P< id>。+)/ $','view'),
...
因为更新时需要overlay_id,它是URL的一部分,而不是查询参数。在django视图中,我想在POST成功后重定向,并使用reverse()避免引用我的python代码中的URL。一般的想法是:
return HttpResponseRedirect(
reverse('views.view',
kwargs = {
'id':id,
},
)
)
但是如何通过反向传递查询参数?
谢谢,
Craig
你不能检查一个 overlay_id
并将其添加到你的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)
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
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屋!