Django模板:如何将项目保存在{%for%}循环中?
问题描述:
This application returns schoolmates of lawyers。Django模板:如何将项目保存在{%for%}循环中?
当用户仅搜索名字和there are more than 1 result我离开查询的形式,并要求他们输入姓氏。但我认为如果用户只需点击其中一个名称并直接返回搜索结果就会更好。 (此时链接会再次搜索表单)。
在模板中,我需要的查询和姓氏是{% for lawyer in lawyers %}
循环内的属性:lawyer.first
和lawyer.last
。我无法弄清楚如何保存它们来创建查询。你能帮我解决这个问题吗?
注意:模板在下面,但我把view function放在pastebin.com。这是60行,我不确定是否应该在这里发布。
谢谢。
<html>
<head>
<title>Search results</title>
</head>
<body>
<p>You searched for <strong>{{ first|capfirst }} </strong>.</p>
<p>There are {{ lawyers|length }} {{ first|capfirst }} in the database. Please select one.</p>
{% for lawyer in lawyers %}
<ul><li><a href="/search/">{{ lawyer.first }} {{ lawyer.last }} {{ lawyer.firm_name }} {{ lawyer.school}} class of {{ lawyer.year_graduated }}</a></li></ul>
{% endfor %}
<form action="" method="get">
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
</body>
</html>
编辑
我需要创造这样一个新的视图功能?
def new_query(request):
last_name = request.GET.get('lawyers.last')
first_name = request.GET.get('lawyer.first')
....
答
由于您使用的是GET表单,因此您可以使用普通链接完全模拟表单提交。
<a href="?first_name={{lawyer.first}}&last_name={{lawyer.last}">
这将发送到当前URL的请求(因为我们没有指定任何URL,只是得到的参数,这是
<form action="" method="get">
等同,但增加了表格2个参数,所谓的first_name和last_name,正如它们以你的正常形式被调用一样 - 这样相同的视图可以处理这个请求
如果你的表单中有其他参数(比如year_of_graduation),你必须添加他们也是。
答
你可以将其添加为GET参数
<a href="/search/?first={{lawyer.first}}&last={{lawyer.last}">
然后通过request.GET
您可以访问所传递的物品。
谢谢。我是否在编辑问题时添加了新的视图功能?你可以提供更多的细节,或让我知道在哪里看? – Zeynel 2010-01-22 18:32:11
@Zeynel:不,你不需要创建一个新的视图。试试吧。 – 2010-01-23 07:26:38