4

我正在使用 Django,在不修改 url 的情况下将变量信息传递回服务器时遇到了麻烦。这就是我想要的方式,除了我希望动作是/foo:

<form method="post" action="/foo/{{ variable }}">
  <input type="submit" value="bar"/>
</form>

当我这样做时,我可以在解析 url 时轻松获取变量。相反,我想将变量添加到 POST QueryDict。这可能吗?

4

5 回答 5

7

是的。只需添加额外的输入字段:

<form method="post" action="/foo/">
  <input type="hidden" value="{{ variable }}" name="name_of_var">
  <input type="submit" value="bar"/>
</form>

然后您可以通过以下方式访问视图中的变量:

request.POST['name_of_var']

或者如果您不确定变量是否存在。这不会引发异常是不存在的。

request.POST.get('name_of_var')
于 2012-10-02T21:04:10.033 回答
3

Just make an input inside your form:

<input type="hidden" value="{{ variable }}" name="foo" />

Then on a view:

foo = request.POST.get('foo', None)

Also, I recomend you to use url tag for action.

于 2012-10-02T21:06:15.523 回答
0

Simply add a hidden input element with the name and value you need like so:

<input type="hidden" name="varname" value="myvalue" />
于 2012-10-02T21:05:24.217 回答
0

Can you not make the variable an input field in the form? You can make it hidden to avoid overriding it. This will post the data in the submit and achieve what you want.

于 2012-10-02T21:05:40.030 回答
0

这不是 Django 会话框架的用途吗?您可以来回传递数据,而无需尝试通过 url 传递数据。

会话框架允许您基于每个站点访问者存储和检索任意数据。它将数据存储在服务器端,并抽象了 cookie 的发送和接收。

https://docs.djangoproject.com/en/1.5/topics/http/sessions/

于 2013-08-06T20:33:03.133 回答