Reputation: 13515
At present the search form is for last name only and that causes problems where there are more than one last name.
This was noted here by Antony Hatchkin.
To solve the problem I want to add a search form with last name and first name and write a new search function search2().
Will the new function look something like this?
def search2(request):
q_last = request.GET.get('q_last', '')
q_first = request.GET.get('q_first','')
lawyers = Lawyer.objects.filter(last__iexact=q_last).first__icontains=q_first)
....
If so how do I get the q_last and q_first from the form?
And this is the view I am using now:
def search(request):
q = request.GET.get('q', '')
if q:
lawyers = Lawyer.objects.filter(last__iexact=q)
if len(lawyers)==0:
return render_to_response('not_in_database.html', {'query': q})
if len(lawyers)>1:
return render_to_response('more_than_1_match.html', {'lawyers': lawyers, 'query': q})
q_school = Lawyer.objects.filter(last__iexact=q).values_list('school', flat=True)
q_year = Lawyer.objects.filter(last__iexact=q).values_list('year_graduated', flat=True)
lawyers1 = Lawyer.objects.filter(school__iexact=q_school[0]).filter(year_graduated__icontains=q_year[0]).exclude(last__icontains=q)
return render_to_response('search_results.html', {'lawyers': lawyers1, 'query': q})
else:
return HttpResponse('Please submit a search term.')
Edit
New field in the form like this?
First name:<form action="/search/" method="get">
<input type="text" name="q_first">
<br />
Last name:<input type="text" name="q_last">
<input type="submit" value="Search">
</form>
Upvotes: 0
Views: 1124
Reputation: 33984
In django forms.Form
are usually used for that:
forms.py:
from django import forms
class ContactForm(forms.Form):
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
When you get used to it, switch to more advanced form:
forms.py:
from django import forms
class ContactForm(forms.ModelForm):
class Meta:
model=Lawyer
fields = 'first_name', 'last_name'
As for using it in a template read docs
Upvotes: 3