gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:58:36 25 4
gpt4 key购买 nike

我正在编写一个 django 应用程序,其 URL 类似于“http://localhost/entity/id/?overlay=other_id”。其中 id 是特定实体的主键,overlay 是要在显示中叠加的第二个实体的可选查询参数。用户只能在通过叠加层查看对象时更新实体。当 POST 到/update/id 时,我想重定向回/entity/id,但我不想在重定向过程中丢失我的查询参数,因为 View 的变化会很刺耳。

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

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

因为更新时需要 overlay_id,所以它是 URL 的一部分,而不是查询参数。在 django View 中,我想在成功 POST 后重定向并使用 reverse() 以避免在我的 python 代码中引用 URL。总体思路是:
return HttpResponseRedirect(
reverse('views.view',
kwargs={
'id': id,
},
)
)

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

谢谢,
克雷格

最佳答案

您可以使用 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()

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

关于Django 使用 reverse() 重定向到依赖查询字符串的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4477090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com