【问题标题】:Django templates: how do I save an item inside a {% for %} loop?Django 模板:如何在 {% for %} 循环中保存项目?
【发布时间】:2010-01-22 18:02:33
【问题描述】:

This application returns schoolmates of lawyers.

当用户仅搜索名字和there are more than 1 result 时,我将查询留在表单中并要求他们输入姓氏。但是我认为如果用户只是单击其中一个名称并直接返回搜索结果会更好。 (此时链接将带您再次搜索表单。)

在模板中,我需要的查询和姓氏在{% for lawyer in lawyers %} 循环中作为属性:lawyer.firstlawyer.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')
    ....

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    由于您在表单中使用 GET,因此您可以完全模拟带有普通链接的表单提交。

    <a href="?first_name={{lawyer.first}}&last_name={{lawyer.last}">
    

    这将向当前 URL 发送请求(因为我们没有指定任何 URL,只是 GET 参数。这相当于

    <form action="" method="get">
    

    但是添加到表单 2 参数,称为 first_name 和 last_name,就像在您的正常表单中调用它们一样 - 这样同一个视图可以处理此请求。

    但是,如果您的表单中有其他参数(例如 year_of_graduation),您也必须添加它们。

    【讨论】:

      【解决方案2】:

      您可以将它们添加为 GET 参数

      <a href="/search/?first={{lawyer.first}}&last={{lawyer.last}">
      

      然后通过request.GET你可以访问传递的项目。

      【讨论】:

      • 谢谢。当我在问题的编辑中添加时,我是否创建了一个新的视图函数?你能提供更多细节或让我知道去哪里看吗?
      • @Zeynel:不,您不需要创建新视图。试试看吧。
      猜你喜欢
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 2021-10-17
      • 1970-01-01
      • 2012-06-27
      • 2011-09-24
      相关资源
      最近更新 更多