我正在嘗試為我的應用程式構建 django 搜索功能,但輸入表單一直回傳無
視圖.py
def search(request):
if request.method == 'POST':
query = request.POST.get('text')
houses = Product.objects.filter(name__contains='query')
context = {
'houses':houses,
}
return render (request, 'searchresult.html', context)
搜索.html
<form>
<input type='text' placeholder='search houses>
<button type='submit'>Search</button>
</form>
uj5u.com熱心網友回復:
首先,你的python縮進無效,你的HTML也無效就input行了。我會假設這是問題中的一個錯字,但如果不是,那你就有問題了。
您的主要問題是房屋過濾器:
houses = Product.objects.filter(name__contains='query')
正在尋找包含字串“query”的名稱。您需要剛剛定義的變數。
houses = Product.objects.filter(name__contains=query)
uj5u.com熱心網友回復:
您發布的代碼中存在縮進問題。
您需要在表單中添加
action和method。<form action="/url_of_search/" method="post">行中缺少報價
input。<input type='text' placeholder='search houses'>您需要在過濾器中使用
query而不是'query'。Product.objects.filter(name__contains=query)
uj5u.com熱心網友回復:
html代碼中缺少的東西:
- 表單動作屬性
- 表單方法屬性
- 輸入欄位名稱屬性
<!-- add form attributes method and action -->
<form method="POST" action="{% url '<url_name>' %}">
<!-- add input attribute name to identify the field and pass the value in request body -->
<input type='text' placeholder='search houses' name='search_text'>
<button type='submit'>Search</button>
</form>
更新搜索視圖
def search(request):
if request.method == 'POST':
# use input field name to get the search text
query = request.POST.get('search_text')
houses = Product.objects.filter(name__contains=query)
context = {
'houses':houses,
}
return render (request, 'searchresult.html', context)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/330717.html
標籤:姜戈
