Python 查询模型工作不正常-Django
我目前正在学习Django,作为练习,我编写了一个简单的模型、一个视图和两个模板。我的应用程序的目的是查询我数据库中“标题”字段中包含特定术语的书籍。我已经为此编写了一个“Book”模型,一个视图函数,用于使用“Book”模型查询书籍,并将结果返回到模板“search results.html”。查询术语是从HTML表单传递的。我能够从'request'对象接收查询字符串,但是当我查询'Book'模型的结果时,我得到一个空列表。我尝试从pythonshell中查询“Book”模型,它运行得非常好。为什么我的视图函数没有得到任何结果?以下是“我的视图”功能中的代码:Python 查询模型工作不正常-Django,python,django,Python,Django,我目前正在学习Django,作为练习,我编写了一个简单的模型、一个视图和两个模板。我的应用程序的目的是查询我数据库中“标题”字段中包含特定术语的书籍。我已经为此编写了一个“Book”模型,一个视图函数,用于使用“Book”模型查询书籍,并将结果返回到模板“search results.html”。查询术语是从HTML表单传递的。我能够从'request'对象接收查询字符串,但是当我查询'Book'模型的结果时,我得到一个空列表。我尝试从pythonshell中查询“Book”模型,它运行得非常好
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Book.objects.filter(title__icontains=q)
return render(request,'search-results.html',{'results':books,'query':q})
else:
message = 'You submitted an empty form'
return HttpResponse(message)
以下是我的搜索表单的代码:
<form action='/search/' method='get'>
<input type='text' name='q'>
<input type='submit' value='Search'>
</form>
以下是结果模板:
<body>
<p>
The following are the {{books|length}} results for the search term {{query}}:
{% for book in books %}
<li>{{book.title}}</li>
{% endfor %}
</p>
</body>
以下是搜索词{query}的{books | length}结果:
{书籍中书籍的百分比%}
{{book.title}}
{%endfor%}
我正在使用Django 1.6和Python 2.7.8、MySQL 5.6
谢谢,,
Rakesh.您将包含书籍的上下文变量称为“结果”,但在模板中,您正在迭代“书籍”。选择一个并保持一致。您正在模板中查询
书籍
,而当您在视图中将变量传递给模板时,您命名变量结果
在模板中,尝试迭代结果
,而不是书籍
:
{% for book in results %}
<li>{{book.title}}</li>
{% endfor %}
{%for book in results%}
{{book.title}}
{%endfor%}
这将导致:
<body>
<p>
The following are the {{results|length}} results for the search term {{query}}:
{% for book in results %}
<li>{{book.title}}</li>
{% endfor %}
</p>
</body>
以下是搜索项{query}的{results | length}结果:
{results%%中图书的%
{{book.title}}
{%endfor%}
结果模板是什么样子的?谢谢你们,新手犯了个错误!
<body>
<p>
The following are the {{results|length}} results for the search term {{query}}:
{% for book in results %}
<li>{{book.title}}</li>
{% endfor %}
</p>
</body>