Reputation: 105
I am making a search form in django, and I am struggling with processing the form in my view.
My code:
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))
I get this error: Cannot resolve keyword u'NAME' into field. Choices are: date_submitted, id, name, parameters.
I realized that this field is in unicode and tried converting it with str(...) or with encode('ascii',...), but it still gives me the same error. I am new to django, so any help would be appreciated.
Thanks
Upvotes: 1
Views: 1176
Reputation: 9474
It complains about the (uppercase) NAME
field, and judging by the error message's format, it is the query that triggers it. I can't really tell from your code, but at some point I think you execute the equivalent of the following:
Group.objects.filter(NAME='some_value')
If the Group model (which you didn't post, so this is an educated guess) contains a lowercase name
field, the above query will generate the error you posted as it tries to access the uppercase NAME
field.
So I guess it boils down to: what does the final query look like? For getting information on that, danihp's comment already provided a good breakdown for how to determine this.
Upvotes: 0
Reputation: 51665
To find your error code replace this code:
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)
By this one:
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 )
But, to have really control over your query, you need to write condition by condition:
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)
Upvotes: 1