gpt4 book ai didi

python - Django 表单搜索

转载 作者:太空宇宙 更新时间:2023-11-03 19:26:59 25 4
gpt4 key购买 nike

我正在 django 中制作一个搜索表单,在我看来,我正在努力处理该表单。

我的代码:

class SearchForm(forms.Form):
name = forms.CharField(label="Name", max_length=64, required=False)
...
<a few other fields>


def search(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
qdict = { 'name': name}
q_objs = [Q(**{qdict[k]: form.cleaned_data[k]}) for k in qdict.keys() if form.cleaned_data.get(k, None)]
search_results = Group.objects.select_related().filter(*q_objs)
response = {'success' : search_results}
return HttpResponse(simplejson.dumps(response, ensure_ascii=False), mimetype='application/javascript')
else:
form = SearchForm()
return render_to_response("main/search.html", {'form': form},
context_instance=RequestContext(request))

我收到此错误:无法将关键字 u'NAME' 解析到字段中。选项有:提交日期、id、名称、参数。

我意识到这个字段是unicode的,并尝试用str(...)或encode('ascii',...)转换它,但它仍然给我同样的错误。我是 django 新手,因此我们将不胜感激。

谢谢

最佳答案

要查找错误代码,请替换此代码:

name = form.cleaned_data['name']
qdict = { 'name': name}
q_objs = [Q(**{qdict[k]: form.cleaned_data[k]}) for k in qdict.keys() if form.cleaned_data.get(k, None)]
search_results = Group.objects.select_related().filter(*q_objs)

通过这个:

q=None
for k,v in form.cleaned_data.items():
if q:
q &= Q( k = v )
else:
q = Q( k = v )
search_results = Group.objects.select_related().filter( q )

但是,要真正控制查询,您需要逐个条件地编写:

qs = []

name = form.cleaned_data['name']
if name:
q_name = Q( name__contains = name )
qs.append(q_name)

fromDate = form.cleaned_data['fromDate']
if fromDate:
q_from = Q( date__gte = fromDate )
qs.append(q_from)

toDate = form.cleaned_data['toDate']
if toDate:
q_toDate = Q( date__gte = toDate )
qs.append(q_toDate)

q=None
for x in qs:
if q:
q &= x
else:
q = x

search_results = Group.objects.select_related().filter(q)

关于python - Django 表单搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7781204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com