如何自动填写搜索表单? [英] How to autocomplete a search form?

查看:142
本文介绍了如何自动填写搜索表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个搜索表单,它的工作正常。现在我想要我的搜索表单autocomplete.I尝试使用django自动完成光,但我有一个问题实现它。



可以使用我现有的代码,添加JavaScript并使其正常工作吗?
我试图自己做,但是我来到了墙上。



我真的很感激,如果有人可以帮助我,给我一个提示或一个链接工作演示或教程。



这是我当前的代码。感谢您的时间。



views.py

  def search请求):
如果请求中的'q'.GET和request.GET ['q']:
q = request.GET ['q']
search_list = Book.objects.filter
Q(title__icontains = q)| Q(description__icontains = q))
返回render_to_response('books / search_results.html',{'search_list':search_list,'query':q},context_instance = RequestContext (request))
else:
return render_to_response('books / please_submit.html',{},context_instance = RequestContext(request))

urls.py

  urlpatterns = patterns('',
url(r'^ search / $','papers.views.search',name ='search'),

search.html

 < form method ='get'action ='/搜索/'> 
< input type ='text'name ='q'class =btn btn-theme btn-sm btn-min-block greaterForm>
< input type ='submit'value ='Search'class =btn btn-theme btn-sm btn-min-block>
< / form>


解决方案

Django自动完成光线很难设置在我看来,它更容易使用其他autocompletes。



这是我使用引导程序2工作的方式(还有一个引导3兼容库,配置或多或少相同 https://github.com/bassjobsen/Bootstrap-3-Typeahead )。



您需要几件事来合作。



1:创建一个将处理自动完成请求并返回建议的视图。
所以在views.py

  def book_autocomplete(request,** kwargs):
term = request .GET .__ getitem __('query')
books = [str(book)for book in book.objects.filter(Q(title__icontains = q)| Q(description__icontains = q))]
return HttpResponse (json.dumps(books))

在urls.py中添加一个条目:

  url(r'^ autocomplete / book_autocomplete /',booking.ebsadmin.book_autocomplete,name ='book_autocomplete'),

2:将引导类型打头/自动填充代码加载到页面中。我继承的项目已经在使用引导程序2,所以这个代码已经在那里了。
所以在你的模板头部分(这可能会根据你的静态文件的目录结构而有所不同):

 < script type =text / javascriptsrc ={{STATIC_URL}} bootstrap / js / bootstrap.min.js>< / script> 
< link rel =stylesheettype =text / csshref ={{STATIC_URL}} bootstrap / css / bootstrap.min.css/>

3:将引导类型头部/自动完成连接到您的视图。
我创建了一个文件book_autocomplete.js,并将其添加到我的静态文件文件夹中。这告诉它将自动填充附加到id书搜索的元素(您将必须在您的表单和id上给出与我在这里使用的'#book-search'等价的搜索框。这在您的表单定义中 https://stackoverflow.com/a/5827671/686016 ):



book_search_typeahead.js

  $(document).ready(function(){
$('#book-search')。typeahead({source:function(query,process){
return $ .getJSON(
'/ autocomplete / book_autocomplete /',// this is the url对于我们在步骤1中创建的视图
{查询:查询},
函数(数据){
console.log(data);
返回进程(数据);
});
}});
});

返回到您的模板,并添加此行加载我们刚刚创建的javascript:

 < script type ='text / javascript'src ='{{STATIC_URL}} book_search_typeahead.js'>< / script> 

我认为这是一切。


I have a search form and it works fine. Now I would like my search form autocomplete.I tried using django autocomplete light but I have a problem implementing it.

Is it possible to use my existing code, add JavaScript and make it work? I tried to do it myself but I came to a wall.

I would really appreciate if someone could help me with this, give me a hint or a link for a working demo or tutorial.

This is my current code. Thanks for your time.

views.py

def search(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        search_list = Book.objects.filter(
    Q(title__icontains=q) | Q(description__icontains=q))
        return render_to_response('books/search_results.html', {'search_list': search_list, 'query': q}, context_instance=RequestContext(request))
    else:
        return render_to_response('books/please_submit.html', {}, context_instance=RequestContext(request))

urls.py

urlpatterns = patterns('', 
    url(r'^search/$','papers.views.search', name='search'),
)

search.html

    <form method='get' action='/search/'>
        <input type='text' name='q'  class="btn btn-theme btn-sm btn-min-block biggerForm"> 
        <input type='submit' value='Search'  class="btn btn-theme btn-sm btn-min-block">
    </form>

解决方案

Django-autocomplete-light is tricky to set up and in my opinion its easier using other autocompletes.

Here is how I got it working using bootstrap 2. (There is a bootstrap 3 compatible library as well, and the configuration is more or less the same https://github.com/bassjobsen/Bootstrap-3-Typeahead).

You need a few things to work together.

1: Create a view that will process the autocomplete request and return suggestions. so in views.py

def book_autocomplete(request, **kwargs):
    term = request.GET.__getitem__('query')
    books = [str(book) for book in    book.objects.filter(Q(title__icontains=q) | Q(description__icontains=q))] 
    return  HttpResponse(json.dumps(books))     

And in urls.py add an entry:

url(r'^autocomplete/book_autocomplete/' , booking.ebsadmin.book_autocomplete , name='book_autocomplete'),

2: Load the bootstrap typeahead/autocomplete code into your page. The project I inherited was already using bootstrap 2, so this code was already there. So in your template in the head section (this will probably differ depending on the the directory structure of your static files):

<script type="text/javascript"  src="{{ STATIC_URL }}bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}bootstrap/css/bootstrap.min.css" />

3: Connect the bootstrap typeahead/autcomplete to your view. I created a file book_autocomplete.js, and added it to my static files folder. This tells it to attach the autocomplete to the element with id book-search (you will have to give the search box on your form and id equivalent to the '#book-search' that I have used here. An example on how to do this in your form definition https://stackoverflow.com/a/5827671/686016):

book_search_typeahead.js

$(document).ready(function() {
    $('#book-search').typeahead({source: function (query, process) {
        return $.getJSON(
            '/autocomplete/book_autocomplete/', // this is the url for the view we created in step 1
             { query : query },
             function (data) {
                console.log(data) ; 
                return process(data);
             });
        }});    
 });

back to your template and add this line to load the javascript that we just created:

  <script type='text/javascript' src='{{ STATIC_URL }}book_search_typeahead.js' ></script>

I think that is everything.

这篇关于如何自动填写搜索表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆