[英]How can I search variables from another template
我在我的主頁模板中,我只有像 google 主搜索頁面這樣的搜索框,現在我想從另一個模板搜索變量並顯示它,但沒有任何反應。 下面是我的代碼
主頁模板
<form action="{% url 'loststuffapp:IndexView' %}" method="GET" value="{{request.GET.q}}" class="navbar-form" role="search" style="margin-left: 25em;">
<input type="text"placeholder="Search....." name="q">
<button type="submit" onclick="/Miscellaneous"><i class="fa fa-search"></i></button>
</form>
主頁視圖
def IndexView(request):
title="Homepage"
return render(request, "loststuffapp/home.html", {"title":title})
雜項模板
<div class="card-body">
<p><label style="font-size:15px; font-weight: bold;color: black;">Jina la nyaraka: </label>{{Doc.docs_name}}</p>
<p><label style="font-size:15px; font-weight: bold;color: black;">Aina ya nyaraka: </label>{{Doc.item_type}}</p>
{% if Doc.image %}
<div class="row">
<div class="col-md-12">
<img class="img-fluid" alt="Responsive image" src ="{{Doc.image.url}}" style="display: flex;" />
</div>
</div>
{% endif %}
<p>{{Doc.date}}</p>
</div>
雜觀
def Miscellaneous(request):
query = request.GET.get('q', '')
qsets=(Q(docs_name__icontains=query)|Q(item_type__icontains=query))
return render(request, "loststuffapp/Miscellaneous.html", context={"documents":Documents.objects.filter(qsets)})
如果我理解正確,您希望將 q 參數從主頁上的表單傳遞到 Miscellaneous 視圖。 目前您的代碼只是在提交表單時調用您的 IndexView 並返回給它。
我猜您希望表單通過將 url 添加到onclick
按鈕來提交到 Miscellaneous 視圖。 我不認為這會像onclick
期望一些 javascript 函數那樣工作。 您的表單提交到您放入表單的 action 屬性中的 url,這就是您的主頁。
因此,最簡單的方法是更改表單的 action 屬性以指向您的 Miscellaneous 視圖:
<form action="{% url 'loststuffapp:Miscellaneous' %}" method="GET" value="{{request.GET.q}}" class="navbar-form" role="search" style="margin-left: 25em;">
<input type="text"placeholder="Search....." name="q">
<button type="submit"><i class="fa fa-search"></i></button>
</form>
備注:我不確定您對 value 屬性或表單的期望
您還可以做的是在提交表單時返回到您的IndexView
並從那里重定向到MiscellaneaousView
,將查詢作為參數傳遞。 但是,從我從您的帖子中讀到的內容來看,這似乎沒有必要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.