在django中实现搜索

时间:2014-09-12 10:51:27

标签: python django search

我有这个html搜索表单,我想将它链接到我的搜索视图以使其正常工作。

<form class="navbar-form navbar-left" role="search" >
    <div class="form-group">
        <input type="text" class="form-control" placeholder="Search" action = "/search/">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

以下是观点。

def searchResults(request, drname):
    # drname = request.GET.get('drname')
    doctors = Doctor.objects.filter(name__contains=drname)
    clinic = Doctor.objects.filter(clinic__name__contains=drname)
    d = getVariables(request)
    d['doctors'] = doctors
    d['doctors_by_clinic'] = doctors
    return render_to_response('meddy1/doclistings.html',d)

urls.py

url(r'^search/(?P<drname>\w+)/$', views.searchResults, name='searchResults'),  

2 个答案:

答案 0 :(得分:4)

  1. HTML。 <form>必须具有action属性,而不是<input>。另外,将搜索字符串作为get参数发送,不要将其包含在url中(将name属性添加到<input>):

    <form class="navbar-form navbar-left" role="search" action="/search/">
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Search" name="drname">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
    </form>
    
  2. urls.py。删除此部分(?P<drname>\w+)/

    url(r'^search/$', views.searchResults, name='searchResults'),
    
  3. views.py。从GET参数获取搜索字符串:

    def searchResults(request):
        drname = request.GET.get('drname')
        doctors = Doctor.objects.filter(name__contains=drname)
        clinic = Doctor.objects.filter(clinic__name__contains=drname)
        d = getVariables(request)
        d['doctors'] = doctors
        d['doctors_by_clinic'] = doctors
        return render_to_response('meddy1/doclistings.html',d)
    

答案 1 :(得分:2)

action位于form元素中,而不是输入。