我在我的网络应用程序上编写了以下代码来搜索表单。现在,如果未找到搜索的对象,我想显示错误。我最后添加了 else 语句,但它显示错误。
def search(request):
qs = Post.objects.all()
location_query= request.GET.get('location')
details_query= request.GET.get('details')
user_query= request.GET.get('user')
days_query= request.GET.get('days')
people_query= request.GET.get('people')
date_query= request.GET.get('date')
gender_query= request.GET.get('gender')
if location_query !='' and location_query is not None:
qs=qs.filter(location__icontains=location_query)
elif details_query !='' and details_query is not None:
qs=qs.filter(detail__icontains=details_query)
elif user_query !='' and user_query is not None:
qs=qs.filter(author__icontains=user_query)
elif days_query !='' and days_query is not None:
qs=qs.filter(no_days__icontains=days_query)
elif people_query !='' and people_query is not None:
qs=qs.filter(no_people__icontains=people_query)
elif date_query !='' and date_query is not None:
qs=qs.filter(tour_date__icontains=date_query)
elif gender_query !='' and gender_query is not None:
qs=qs.filter(Gender_prefer__icontains=gender_query)
context = {
'qs':qs,
}
return render(request, 'posts/search.html',context)
我想在最后添加这个:
return render(request, 'posts/search.html', {'error':'The keyword you entered not found!})
答案 0 :(得分:0)
对于您的代码,如果您想在上下文中添加错误,请使用此逻辑。
所以代码看起来像这样:
if qs:
context = {
'qs':qs,
}
else:
context = {
'error': 'The keyword you entered not found!'
}
return render(request, 'posts/search.html',context)