我正在尝试在我的django网站上添加一个简单的搜索表单。当我点击搜索按钮时,我被重定向到new_search.html页面(应该是这样),但该页面没有显示任何结果。感谢您的帮助!
代码是这样的:
我有一个主页,我把搜索表单放成这样:
<form method="get" action="{% url 'new_search' %}">
{%csrf_token%}
<input type="text" name="srh" class= "form-control" placeholder="Search">
<button type="submit" name="submit">Search</button>
</form>
当用户搜索某些内容时,结果应显示在new_search.html页面中。我在 views.py 中编写的函数是这样的:
def new_search(request):
if request.method == 'GET':
srch = request.GET.get('srh')
if srch:
sr = Info.objects.filter(Q(band__icontains=srch) | Q(disco__icontains=srch))
if sr:
return render(request, 'new_search.html', {'sr':sr})
else:
messages.error(request, 'no results')
else:
return render(request, 'new_search')
return render(request, 'new_search.html')
new_search.html页面是这样的:
<div>
{% if sr %}
{% for k in sr %}
<table width="200px">
<tr><td>Band</td><td>{{k.band}}</td></tr>
<tr><td>Album</td><td>{{k.disco}}</td></tr>
</table>
{%endfor%}
{%endif%}
</div>
model.py 是这样的:
class Info(models.Model):
band = models.CharField(max_length=200, help_text="Write Here")
disco = models.CharField(max_length=200, help_text="Write Here")
etichetta_p = models.CharField(max_length=200, help_text="Write Here")
etichetta_d = models.CharField(max_length=200, help_text="Write Here")
matrice = models.CharField(max_length=200, help_text="Write Here")
anno = models.PositiveIntegerField(default=0)
cover = models.ImageField(upload_to='images/')
def __str__(self):
return self.band
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('search.urls')),
path('accounts/', include('django.contrib.auth.urls')),
哔哔one
相关分类