我正在尝试在我的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.bandurls.pyurlpatterns = [ path('admin/', admin.site.urls), path('', include('search.urls')), path('accounts/', include('django.contrib.auth.urls')),
1 回答
哔哔one
TA贡献1854条经验 获得超8个赞
在我看来,你应该在类视图中处理方法,因为你正在使用一个,例如:POST
class new_searchView(TemplateView):
template_name = "new_search.html"
def post(self, request, *args, **kwargs):
print('FORM POSTED WITH {}'.format(request.POST['srh']))
return render(self.request, 'new_search.html')
添加回答
举报
0/150
提交
取消