Django Front End Search
Currently using Django 2.1,Python 3.6, PostgreSQL 11, and hosting the DB on Heroku. I would like to implement a user search on a device view that I have setup. Current Page Layout
Solution 1:
You can use this example to implement your own search engine in your views
defsearch(request):
keywords=''if request.method=='POST': # form was submitted
keywords = request.POST.get("keywords", "") # <input type="text" name="keywords">
all_queries = None
search_fields = ('title','content','resume') # change accordinglyfor keyword in keywords.split(' '): # keywords are splitted into words (eg: john science library)
keyword_query = Nonefor field in search_fields:
each_query = Q(**{field + '__icontains': keyword})
ifnot keyword_query:
keyword_query = each_query
else:
keyword_query = keyword_query | each_query
ifnot all_queries:
all_queries = keyword_query
else:
all_queries = all_queries & keyword_query
articles = Article.objects.filter(all_queries).distinct()
context = {'articles':articles}
return render(request, 'search.html', context)
else: # no data submitted
context = {}
return render(request, 'index.html', context)
You just have to change the following :
1 - The name attribute used in html
<inputtype="text" name="keywords">
keywords = request.POST.get("keywords", "")
2 - The name of the model class
3 - The search fields of that model
Then in your search.html template
<table>
<tr>
<td>Title</td>
<td>Author </td>
</tr>
{% for article in articles %}
<tr>
<td>{{article.title}}</td>
<td>{{article.author}}</td>
</tr>
{% endfor %}
</table>
Post a Comment for "Django Front End Search"