在django模板表单中创建一个值

时间:2014-07-04 09:51:10

标签: django django-forms django-templates django-views

我将对象的查询集传递给模板。如何在提交表单时将该查询集传递回视图?

这就是我所拥有的:

{% for engine in engines %}
{{engine.manufacturer}}: {{engine.name}}
{% endfor %}
...
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="hidden" name="engine_ids" value="{{engines}}"/>
<input type="submit" value="Export engines" name="export"/>
</form>

通常request.POST.getlist('engine_ids')会返回字符串

[<Engine: Engine Object>, <Engine: Engine Object>, <Engine: Engine Object>, <Engine: Engine Object>, ... '...(remaining elements truncated)...']

哪个没用,所以我做了一个脏的廉价黑客并更改了模型__unicode__函数来返回id。

现在我明白了:

[<Engine: 2>, <Engine: 4>, <Engine: 7>, <Engine: 9>, ... '...(remaining elements truncated)...']

这更有用,因为我现在可以从这些ID生成查询集。但是使用这种方法,我只限于20个元素; 20之后的任何内容显示为'...(remaining elements truncated)...'

我的问题是,有什么方法可以做到这一点?如果我可以做像

那样的事情会很棒
{% for engine in engines %}
{{engine.manufacturer}}: {{engine.name}}
**add engine.id to a list called engine_id_list**
{% endfor %}
...
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="hidden" name="engine_ids" value=**engine_id_list**/>
<input type="submit" value="Export engines" name="export"/>
</form>

2 个答案:

答案 0 :(得分:1)

啊,我想通了;

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="hidden" name="engine_ids" value="{% for engine in engines %}{{engine.id}},{% endfor %}"/>
<input type="submit" value="Export engines" name="export"/>
</form>

答案 1 :(得分:0)

import json
...
return render(request, 'template', {'engine_id_list': json.dumps([e.id for e in Engine.objects.filter(thefilter)])}