使用ajax在python中自动完成搜索框

时间:2016-01-13 10:23:12

标签: jquery python ajax django

这是我的代码:

model.py

class Bookmark(models.Model):

  

url = models.URLField()
      title = models.CharField('title', max_length=255)
      description = models.TextField('description', blank=True)
      is_public = models.BooleanField('public', default=True)
      date_created = models.DateTimeField('date created')
      date_updated = models.DateTimeField('date updated')
      owner = models.ForeignKey(User, verbose_name='owner', related_name='bookmarks')
      tags = models.ManyToManyField(Tag, blank=True)
      views = models.IntegerField(default=0)
      objects = models.Manager()
      public = PublicBookmarkManager()

class Meta:
    verbose_name = 'bookmark'
    verbose_name_plural = 'bookmarks'
    ordering = ['-date_created']

def __str__(self):
    return '%s (%s)' % (self.title, self.url)

def save(self, *args, **kwargs):
    if not self.id:
        self.date_created = now()
    self.date_updated = now()
    super(Bookmark, self).save(*args, **kwargs)`

views.py

def bookmark_search(request):

  

query_string = ''
      found_entries = None
      if ('q' in request.GET) and request.GET['q'].strip():

    query_string = request.GET['q']

    entry_query = get_query(query_string, ['id', 'url', 'title'])

    found_entries = Bookmark.objects.filter(entry_query).order_by('-date_created')
context = { 'query_string': query_string, 'found_entries': found_entries }
return render(request,'marcador/bookmark_search.html',context)`

urls.py

urlpatterns = [

  

url(r'^search/?$', 'marcador.views.bookmark_search', name='marcador_bookmark_search'),   ]

bookmark_search.html

{% block search %}
{% url "marcador_bookmark_search" as action_url %}
<form class="navbar-form navbar-right search" role="form" method="get" action="{{ action_url }}" accept-charset="utf-8">

  

<div class="form-group">
      <label for="id_q"></label>
      <input type="text" id="id_q" placeholder="Search..." class="form-control" name="q">
      <input type="submit" class="btn btn-default" value="GO"/>
      </div>
  </form>
  {% endblock %}

我有这个代码,我正在搜索提交搜索框的按钮。 但是现在我想直接显示数据库数据,当我点击搜索框并使用Ajax写一些后者时。

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用jquery-autocomplete-light:

执行此操作
  1. 获取jquery-autocomplete-light's autocomplete.js,确保其已加载到HTML页面中,如果您还不熟悉,请参阅django on staticfiles,如果您还是困惑,试试surviving staticfiles howto

  2. 在自动填充框内创建视图,example

  3. 在HTML页面中使用脚本标记配置autocomplete.js,example

  4. 在右上方搜索框的ilstravaillentpourvous.fr中使用了这个,因为此网站是开源的,您还可以inspect itautocomplete.js configurationautocomplete view,{ {3}},autocomplete template