django 搜索功能的实现

参考文章:
简单搜索功能实现:https://www.zmrenwu.com/post/19/
复杂搜索功能实现,使用django-haystach:https://github.com/django-haystack/django-haystack

views.py:

  # 搜索功能实现
       q = request.GET.get('q', '')
       error_msg = ''
       if not q:
           error_msg = '请输入搜索关键字'
       if q:
           objects = Law.objects.filter(title__contains=q)

       # 分页
       try:
           page = request.GET.get('page', 1)
       except PageNotAnInteger:
           page = 1

       p = Paginator(objects, per_page=5, request=request)
       laws = p.page(page)

       return render(request, 'zcfg-list.html', {
           'laws': laws,
           'type': type,
           'error_msg': error_msg,
           'q': q,
       })

templates中的forms:

<form class="input-group" method="get" action="{% url 'lawlist' %}">
    <input type="text" class="form-control" name="q" placeholder="输入搜索内容...">
    <span class="input-group-btn">
      <button class="btn btn-default" type="submit">搜索button>
    span>
    {% csrf_token %}
form>

你可能感兴趣的:(django,django,搜索功能实现)