Django表单:如何从HTML表单中获取名字和姓氏?

时间:2010-01-14 20:29:35

标签: django django-forms

目前,搜索表单仅用于姓氏,并且会导致超过one last name的问题。

Antony Hatchkin注意到here

要解决此问题,我想添加一个带有姓氏和名字的搜索表单,并编写一个新的搜索功能search2()。

新功能看起来像这样吗?

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)
....

如果是这样,我如何从表单中获取q_last和q_first?

这就是我现在使用的观点:

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.')

修改

这样的形式的新字段?

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>

1 个答案:

答案 0 :(得分:3)

在django中forms.Form通常用于:

forms.py:

from django import forms

class ContactForm(forms.Form):
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)

当你习惯它时,切换到更高级的形式:

forms.py:

from django import forms

class ContactForm(forms.ModelForm):
    class Meta:
        model=Lawyer
        fields = 'first_name', 'last_name'

至于在模板中使用它,请阅读docs