通过 URL 将项目列表传递给视图
我有一个如下所示的项目列表:'Item 1', 'Item 2', 'Item 3'...
列表的长度是动态的。
我的问题是如何将此变量传递到我的视图?
编辑1 只是想我会澄清我正在尝试的内容:
return HttpResponseRedirect(reverse('newFeatures',
kwargs={'stock_number': stock_number, 'new_features': new_features}))
new_features
是我的动态列表,而 newFeatures
是一个像这样开始的视图:
def add_new_feature(request, stock_number, new_features):
不确定这是否有意义,但我希望它能帮助我走出黑暗
I have a list of items that looks like this: 'Item 1', 'Item 2', 'Item 3'...
with the list being dynamic in length.
My question is how can I pass this variable to my view?
Edit 1
Just thought I'd clarify what I was attempting:
return HttpResponseRedirect(reverse('newFeatures',
kwargs={'stock_number': stock_number, 'new_features': new_features}))
With new_features
being my dynamic list, and newFeatures
being a view that starts like this:
def add_new_feature(request, stock_number, new_features):
Not sure if this is making sense, but I hope it'll help get me out of the dark
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HttpResponseRedirect 只是返回 HTTP 302 重定向响应,该响应重定向到另一个 url。您无法通过重定向发送任何类型的 POST 数据,因此如果您想包含任何变量,它必须是您重定向到的 url 的一部分。
如果您坚持在重定向之前不处理列表,那么最好的选择可能是将列表转换为字符串并将其用作 url 中的参数。然后 newFeatures 函数可以将该字符串解析回项目列表。
HttpResponseRedirect simply returns an HTTP 302 redirect response, which redirects to another url. You cannot send any kind of POST data with the redirect, so if you want to include any variables, it must be part of the url you redirect to.
If you insist on not processing the list before redirecting, then you best option would probably be to convert the list into a string and use it as a parameter in the url. The newFeatures function could then parse that string back into a list of items.
怎么样:
and:
这假设
new_features
中的元素仅包含对 URL 安全的字符,并且不包含逗号。如果情况并非如此,那么您将必须执行某种形式的转义。请记住,不建议使用 GET 样式的 URL 更改其目标的状态。为此,您应该使用 POST,这会阻止您通过 URL 传递参数(即通过
reverse()
)。此外,有时服务器对 URL 长度有限制,这可能会妨碍 GET。How about:
and:
This assumes the elements in
new_features
consist only of characters that are safe for URLs, and do not contain commas. If this is not the case, then you'll have to perform escaping of some form.Bear in mind that it's not recommended for GET-style URLs to change the state of their targets. You should use POST for that, which would prevent you from passing parameters via the URL (i.e. via
reverse()
). Also, sometimes servers have limits on URL length, which can get in the way of a GET.