我的模板中有一个表单(不是Django表单)
我的观点:
def advanced_search(request):
publish_houses = PublishHouse.objects.all()
authors = Author.objects.all()
context = {
'publish_houses': publish_houses,
'authors': authors,
'Category_Choice': Category_Choice,
}
return render(request, 'books/advanced_search.html', context)
仅显示搜索表单
并用于显示结果:
def result(request):
publish_houses = PublishHouse.objects.all()
authors = Author.objects.all()
queryset_list = Book.objects.order_by('-book_date')
# Title
if 'title' in request.GET:
title = request.GET['title']
if title:
queryset_list = queryset_list.filter(title__icontains=title)
# Author
if 'author' in request.GET:
author = request.GET['author']
if author:
queryset_list = queryset_list.filter(author__name__iexact=author)
# Category
if 'category' in request.GET:
category = request.GET['category']
if category:
queryset_list = queryset_list.filter(classification__iexact=category)
# Publish house
if 'publisher' in request.GET:
publisher = request.GET['publisher']
if publisher:
queryset_list = queryset_list.filter(publish_house__name__iexact=publisher)
# Price
if 'min_price' and 'max_price' in request.GET:
min_price = request.GET['min_price']
max_price = request.GET['max_price']
if min_price and max_price:
queryset_list = queryset_list.filter(price__gte=min_price, price__lte=max_price)
context = {
'publish_houses': publish_houses,
'authors': authors,
'Category_Choice': Category_Choice,
'books': queryset_list,
'values': request.GET,
}
return render(request, 'books/result.html', context)
,我想检查所有字段中是否没有数据,如果没有数据,请重定向回高级搜索表单
我试图将字段的数据放在一个变量中,例如:
title = request.GET['title']
然后通过if not
检查每个字段,但这给了我MultiValueDictKeyError
任何想法我该怎么做?
预先感谢
答案 0 :(得分:1)
使用get
方法提供默认值以防止出现错误。
def result(request):
publish_houses = PublishHouse.objects.all()
authors = Author.objects.all()
queryset_list = Book.objects.order_by('-book_date')
keys = ['title' , 'author', 'category', 'publisher', ('min price', 'max price')]
argument_mapper = {
'title': 'title__icontains',
'author': 'author__name__iexact',
'category': 'classification__iexact',
'publisher': 'publish_house__name__iexact',
('min price', 'max price'): ('price__gte', 'price__lte'), # leave the comma so this is extendable
}
for field in keys:
arg = argument_mapper.get(field)
if isinstance(arg, str):
val = request.GET.get(arg, None)
if val:
queryset_list = queryset_list.filter(**{arg:val})
elif isinstance(arg, tuple):
vals = [request.GET.get(a, None) for a in arg]
if all(vals):
queryset_list = queryset_list.filter(**dict(zip(arg, vals)))
context = {
'publish_houses': publish_houses,
'authors': authors,
'Category_Choice': Category_Choice,
'books': queryset_list,
'values': request.GET,
}
return render(request, 'books/result.html', context)