我正在嘗試在我的django網(wǎng)站上添加一個(gè)簡(jiǎn)單的搜索表單。當(dāng)我點(diǎn)擊搜索按鈕時(shí),我被重定向到new_search.html頁(yè)面(應(yīng)該是這樣),但該頁(yè)面沒(méi)有顯示任何結(jié)果。感謝您的幫助!代碼是這樣的:我有一個(gè)主頁(yè),我把搜索表單放成這樣:<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>當(dāng)用戶搜索某些內(nèi)容時(shí),結(jié)果應(yīng)顯示在new_search.html頁(yè)面中。我在 views.py 中編寫(xiě)的函數(shù)是這樣的: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頁(yè)面是這樣的: <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貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
在我看來(lái),你應(yīng)該在類(lèi)視圖中處理方法,因?yàn)槟阏谑褂靡粋€(gè),例如: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')
添加回答
舉報(bào)
0/150
提交
取消