开发者

search form with django+python

开发者 https://www.devze.com 2023-01-27 05:35 出处:网络
I have just started to do a website with django + python and I want to implement a se开发者_如何学Pythonarch form to be able to search on all my database objects. What I want is; when I write for an e

I have just started to do a website with django + python and I want to implement a se开发者_如何学Pythonarch form to be able to search on all my database objects. What I want is; when I write for an example S I want the search field to display all my objects that starts with the letter S in a list, just like the Tags field below on this site.

Does anyone have a good ide to implement this with django?


For a decent django search implementation, I would recommend looking at djapian. However, for what you are doing, I would recommend a query using the ISTARTSWITH parameter. Consider the following:

views.py

def search(req):
    if req.GET:
        search_term = req.GET['term']
        results = ModelToSearch.objects.filter(field__istartswith=search_term)
        return render_to_response('search.html', {'results': results})
    return render_to_response('search.html', {})

search.html

<html>
<body>
<form>
     <input name='S'>
</form>
{% if results %}
Found the following items:
<ol>
{% for result in results %}
    <li>{{result}}</li>
{% endfor %}
</ol>
{% endif %}
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消