在添加基本搜索栏以搜索菜单列表中的菜单标题的过程中,我收到此错误
django.core.exceptions.FieldError: Cannot resolve keyword 'title_icontains' into field. Choices are: id, menu_title, price, title_content
我是否必须为搜索制作模型?
我在basic.html中的表单视图看起来像这样
<form class="form-inline my-2 my-lg-0" action="/search/" method="get">
<input class="form-control mr-sm-2" type="search" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="Search">Search</button>
</form>
我的views.py
from django.shortcuts import render
from django.http import HttpResponse,Http404,HttpResponseRedirect,HttpResponseNotFound
from resturant.models import Carousel
from resturant.models import Menu
from django.db.models import Q
from django import forms
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
menu_item = Menu.objects.filter(title_icontains = q)
return render(request, 'sources/search_results.html',{'menu_item':menu_item, 'query': q})
else:
return HttpResponse('Please submit a search term.')
我的search_results.html
{% if menu_item %}
<p>Found {{ menu_item|length }} item{{ menu_item|pluralize }}.</p>
<ul>
{% for s in menu_item %}
<li class="wow fadeInUp" data-wow-duration="300ms" data-wow-delay="300ms">
<div class="item">
<div class="item-title">
<h2>{{ s.menu_title }}</h2>
<div class="border-bottom"></div>
<span>$ {{s.price}}</span>
</div>
<p>{{s.title_content}}</p>
</div>
</li>
{% endfor %}
</ul>
{% else %}
<p>No Menu_Items matched your search criteria.</p>
{% endif %}
而我的urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth.views import login
urlpatterns =[
url(r'^$', views.index , name= "index"),
url(r'^menu/$', views.menu , name= "menu"),
url(r'^check/$',views.check,name='check'),
url(r'^search/$',views.search, name='search')
]
很抱歉没有发布菜单模型,它看起来像这样
class Menu(models.Model):
menu_title = models.CharField(max_length = 100,)
price = models.IntegerField()
title_content = models.CharField(max_length = 500,)
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
menu_item = Menu.objects.filter(menu_title_icontains = q)
return render(request, 'sources/search_results.html',{'menu_item':menu_item, 'query': q})
else:
return HttpResponse('Please submit a search term.')
将menu_item = Menu.objects.filter(title_icontains = q)
改为menu_item = Menu.objects.filter(menu_title_icontains = q)
确保字段名称和“icontains”之间有2个下划线符号:
menu_item = Menu.objects.filter(title__icontains = q)