我第一次进入Django,允许用户输入一周中的某一天,并在我的数据库中搜索在该特定日期打开的餐馆。现在,餐馆对象(Resto
)有一个days_open
属性,每天用逗号分隔(星期一,星期二等等)。
当我输入一天时,结果页面只显示标题和'[]',我似乎无法返回Resto
对象列表。什么是显示方括号,如何修复它以显示搜索结果?
如果我忽略了包含任何相关位,那么代码就在我的道歉之下。
my forms.py:
from django import forms
from .models import Resto
class RestoSearch(forms.ModelForm):
class Meta:
model = Resto
fields = ('title', 'description', 'opening_hour', 'closing_hour')
models.py:
from django.db import models
class Resto(models.Model):
title = models.CharField(max_length=300)
description = models.TextField()
opening_hour = models.TimeField(auto_now=False, auto_now_add=False, null=True)
closing_hour = models.TimeField(auto_now=False, auto_now_add=False, null=True)
days_open = models.TextField(blank=True)
views.py:
from django.shortcuts import render
from django.http import Http404
from django.shortcuts import HttpResponse
from belize.models import Resto
from django.core.exceptions import *
from .forms import RestoSearch
def index(request):
return render(request, 'form.html')
def search(request):
form = RestoSearch()
if request.method == 'POST':
search_id=request.POST.get('textfield', None)
try:
#I think this is where my problem is
available = Resto.objects.filter(days_open = search_id)
html = ("<H1>Hello</H1>", available)
return HttpResponse(html)
except Resto.DoesNotExist:
return HttpResponse("Please try another day")
else:
return render(request, 'belize/form.html')
def restaurant_detail(request, id):
try:
restaurant = Resto.objects.get(id=id)
except Resto.DoesNotExist:
raise Http404('This restaurant does not exist')
return render(request, 'belize/restaurant_detail.html', {
'restaurant': restaurant,
})
模板form.html:
<form method="POST" action="/search/">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Enter a day of the week</button>
</form>
答案 0 :(得分:1)
我假设您要显示的是RestoForm
,在这种情况下,索引方法不正确。它应该是
def index(request):
form = RestoForm()
return render(request, 'form.html', {'form': form })
然后您的模板应更改为
<form method="POST" action="/search/">
{% csrf_token %}
{{ form }}
<button type="submit">Enter a day of the week</button>
</form>
有关其他详细信息,请参阅https://docs.djangoproject.com/en/1.9/topics/forms/#the-template
上的示例答案 1 :(得分:0)
[]
表示您的.filter()
未返回任何结果,因为您的代码存在一些问题,这并不奇怪,让我们从顶部开始:
.filter()
我也注释了你的代码:
def search(request):
form = RestoSearch() # You aren't using this form anywhere in your code?
if request.method == 'POST':
# Where is 'textfield' coming from?
search_id = request.POST.get('textfield', None)
try:
# If search id is "Tuesday", and a restaurant is
# open on monday and tuesday, so it has "Monday,Tuesday"
# in the days_open field, then this search will not
# return any results, because its looking for an exact
# match
available = Resto.objects.filter(days_open=search_id)
html = ('<H1>Hello World</H1>', available)
return HttpResponse(html)
except Resto.DoesNotExist:
# This exception is not raised by .filter(),
# .filter() will return an empty list, [] if no results are found
# so this entire try/except is not doing anything
return HttpResponse("Please try another day")
else: # in your code, this else is not indented correctly
return render(request, 'belize/form.html')
所以这里有很多事情,让我们尝试一些简单的事情,从模板开始:
{% if results %}
{% for restaurant in results %}
{{ restaurant }}
{% endfor %}
{% else %}
Sorry, no results for your search. Try again.
{% endif %}
<form>
{{ form }}
<input type="submit" name="Search" />
</form>
接下来,搜索表单:
class SearchForm(forms.Form):
search_field = forms.CharField('Search', strip=True)
最后的观点:
from django.db.models import Q
def search(request):
form = SearchForm(request.GET)
results = [] # Set results to an empty list
if form.is_valid():
needle = form.cleaned_data['search_field'].capitalize()
results = Resto.objects.filter(Q(days_open__startswith='{},'.format(needle)) |
Q(days_open__endswith=',{}'.format(needle)) |
Q(days_open__contains=',{},'.format(needle)) |
Q(days_open='{},'.format(needle)) |
Q(days_open='{}'.format(needle)))
return render(request, 'search.html', {'results': results, 'form': form})
让我们假设用户输入'Thursday'
作为搜索字段。在此视图中,您要搜索所有days_open
字段:
Thursday,
或,Thursday
或,Thursday,
或Thursday,
或Thursday
如果要显示任何值,您的模板将仅显示结果;由于空列表[]
为false,因此{% if results %}
条件将失败,因此在空列表中,模板将显示错误通知。
在您看来,您只会检查数据库是否有人在搜索字段中输入内容,if form.is_valid():
是什么。在django中,默认情况下所有表单字段都是必需的 - 因此空白表单将返回错误。使用此技巧,我们确保只搜索有人在搜索框中输入值。
主要操作发生在所有Q()
次调用中。 Q对象是一种进行多个查询并将它们链接在一起的方法。只要你想做一个&#34;或&#34;就可以使用它。或&#34;和&#34;类型查询。我们的搜索是&#34;或&#34;类型查询,因为如果days_open
中的值与任意数量的条件匹配,我们想要返回任何结果。