Django使用reverse()重定向到依赖于查询字符串的URL [英] Django redirect using reverse() to a URL that relies on query strings

查看:488
本文介绍了Django使用reverse()重定向到依赖于查询字符串的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用像http:// localhost / entity / id /?overlay = other_id这样的URL来编写一个django应用程序。其中,id是特定实体的主键,overlay是用于在显示中覆盖的第二个实体的可选查询参数。用户只能通过叠加层查看对象时更新实体。当POST到/ update / id时,我想重定向到/ entity / id,但是我不想在重定向期间丢失我的查询参数,因为视图的更改会刺激。



例如,我的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆