Python 未显示搜索结果
我创建了一个名为Product的模型,该模型由以下字段组成:“产品名称”、“公司”、“数量”、“价格”、“单位”、“产品类型”,因此每当我使用搜索栏搜索公司名称时,它都不会显示产品 这是我的视图。py文件仅包含搜索视图Python 未显示搜索结果,python,html,django,search,Python,Html,Django,Search,我创建了一个名为Product的模型,该模型由以下字段组成:“产品名称”、“公司”、“数量”、“价格”、“单位”、“产品类型”,因此每当我使用搜索栏搜索公司名称时,它都不会显示产品 这是我的视图。py文件仅包含搜索视图 from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import TemplateView, ListView from django.db.mode
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import TemplateView, ListView
from django.db.models import Q
from .models import *
from .forms import *
class SearchResultsView(ListView):
model = Product
template_name = 'search_results.html'
def get_queryset(self):
query = self.request.GET.get('q')
items=Product.objects.filter(Q(company__icontains=query))
return items
包含搜索栏的base.html文件
<form class="form-inline my-2 my-md-0" action="{% url 'search_results' %}" method="get">
<input class="form-control" name="q" type="text" placeholder="Search">
</form>
这是我搜索某物后的样子
{% extends 'base.html' %}
{% block body %}
<br>
<br>
<table class="table table-hover">
<thead>
<tr>
<th>Sr. No.</th>
<th>Product Name</th>
<th>Company</th>
<th>Quantity</th>
<th>Price</th>
<th>Units</th>
<th>Product Type</th>
</tr>
</thead>
<tbody>
{% for item in items %}
<tr>
<td>{{item.pk}}</td>
<td>{{item.prod_name}}</td>
<td>{{item.company}}</td>
<td>{{item.quantity}}</td>
<td>{{item.price}}</td>
<td>{{item.units}}</td>
<td>{{item.prod_type}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
from django.conf.urls import url
from django.urls import path
from .views import *
urlpatterns=[
path('search/', SearchResultsView.as_view(), name='search_results'),
]
# you just have to remove "Q" from your query
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import TemplateView, ListView
from .models import *
from .forms import *
class SearchResultsView(ListView):
model = Product
template_name = 'search_results.html'
def get_queryset(self):
query = self.request.GET.get('q')
items=Product.objects.filter(company__icontains=query)
return items
# In your template, you have a change
{% for item in object_list %}
<tr>
<td>{{item.pk}}</td>
<td>{{item.prod_name}}</td>
<td>{{item.company}}</td>
<td>{{item.quantity}}</td>
<td>{{item.price}}</td>
<td>{{item.units}}</td>
<td>{{item.prod_type}}</td>
</tr>
{% endfor %}