嘿,我是Django的新手,我正试图在我的第一个网站上添加搜索栏。 我的问题是,当我搜索我/用户输入的任何值并且在网站上时,该网站只会刷新并且不给我任何回报,但是当没有内容匹配时我给网站显示的空选项搜索。
(这不是所有的Topic模型)
model.py
class Topic(models.Model):
content = models.CharField(max_length=200)
views.py
def search(request):
query = request.GET.get('q')
if query:
result = Topic.objects.filter(content__icontains=query)
context = { 'query': query, 'result': result}
return render(request, 'learning_logs/topics.html', context)
(这就是所有topic.html,我很抱歉它如何变成了原来的topic.html上的样子,但这就是完整的topic.html)
topics.html
% extends "leaning_logs\base.html" %}
{% block page_header %}
<h1>Topics </h1>
<br><a href="{% url 'learning_logs:new_topic' %}">Add a new topic</a></br>
{% endblock page_header %}
{% block content %}
<form method="GET" action="{% url 'learning_logs:search' %}">
{% csrf_token %}
<input name="q" value="{{ request.GET.q }}" placeholder="search..">
<button class="btn btn-success" type="submit">
Search</button>
</form>
{% for topic in topics %}
<div class="card-mb3">
<div class="card-header" style="background-color:lightgrey">
<table class="table">
<tr>
<th>Image</th>
<th>Title of the topic</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<div class="card-body" style="background- color:white">
<tr>
<td>
{% if topic.image %}
<image src="{{topic.image.url}}" style="width:200px">
{% else %}
<span class="text-muted">No Image have been added</span>
{% endif %}
<td><h3>
<a href="{% url 'learning_logs:topic' topic.id %}" style="float:center">{{topic}}</a>
</td></h3>
<td><small><a href="{% url 'learning_logs:edit_topic' topic.id %}">
<button method="submit" class="btn btn-primary">
Edit topic</button></a></small></td>
<td><small><form method="post" action="{% url 'learning_logs:delete_topic' topic.id %}">
<button type="submit" class="btn btn-danger btn-primary" >
Delete topic</button></form></small></td>
</tr>
</div>
</div>
</div>
{% empty %}
<h3><li>No topics have been added yet.</li></h3>
{% endfor %}
{% endblock content %}
答案 0 :(得分:1)
此:
{% for topic in topics %}
应该是:
{% for topic in result %}