使用Django / Jquery进行预输入搜索无法正常工作

时间:2018-09-24 04:37:09

标签: python jquery django typeahead.js

我有一个搜索栏,正在使用typeahead.js在Django应用程序中获取自动完成的模型,但是我在单击自动完成的结果以进入模型详细信息页面时需要一些帮助。现在,您无法单击它或搜索结果。我将发布我的视图和模板。谢谢您的协助。

views.py

def get_members(request):
if 'query' in request.GET:
    q = request.GET.get('query', '').capitalize()
    member_list = []
    member_dict = {}
    members = Member.objects.all().filter(
        Q(last_name__icontains=q) |
        Q(first_name__icontains=q) |
        Q(number__icontains=q)
        ).distinct()
    for m in members:
        member_list.append(m.search_result)
    member_dict['options'] = member_list
    data = json.dumps(member_dict)
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)
return HttpResponse()

注意:在append(m.search_result)上,这是一个模型属性,我确定不建议这样做,并将在下面发布。我也希望在这里有更好的方法。

models.py

@property
def search_result(self):
    "Returns the member's number: full name in autocomplete search."
    return '%s: ' '%s %s' % (self.number,self.first_name,self.last_name)

*html template*
{% csrf_token %}
<input type="search" name="searched_item" id="searched_item" class="form- 
control" autocomplete="off" placeholder="Enter member name to be searched 
(eg. John Smith)" style="max-width: 700px;width: 700px;color: 
threeddarkshadow;">
    <script>
    $(document).ready(function($) {
      $('#searched_item').typeahead({
        items:12,
        source: function (query, process) {
          return $.get('/membership/search/', { query: query }, function (data) {
            return process(data.options);
          });
        },
        minLength:1,
        autoSelect:false,

        highlighter: function (item) {
          var regex = new RegExp( '(' + this.query + ')', 'gi' );
          return item.replace( regex, "<strong style='color:#7dcc79;' >$1</strong>" );
        },
      });
    })
  </script>

urls.py

path('search/',views.search_members,name='autocomplete member names')

0 个答案:

没有答案