Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search Bar in Django

Tags:

EDIT: I managed to include a Search bar using 'DjangoFilter'

I would like to add a search bar to my template in Django

I would like to include a search box in above a list of articles so users can search through the data.

When I enter something in the bar nothing happens though...
here below my code

Thanks for the help in advance In HTML page

    <form class="form-inline my-2 my-lg-0">
    <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" >
    <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>

In views.py

def article_overview(request):
    search_term = ''

    if 'search' in request.GET:
        search_term = request.GET['search']
        articles = Article.objects.all().filter(feeder__icontains=search_term) 

    articles = Article.objects.all()

    return render(request, 'overviews/overview.html', {'articles' : articles, 'search_term': search_term })    

in overview.html(simplified):

{% for article in articles %}
<a> {{article.feeder}} </a> 
{% endfor %}
like image 608
TMD Avatar asked Feb 13 '19 19:02

TMD


1 Answers

In views.py,

class SearchView(ListView):
    model = Article
    template_name = 'search.html'
    context_object_name = 'all_search_results'

    def get_queryset(self):
       result = super(SearchView, self).get_queryset()
       query = self.request.GET.get('search')
       if query:
          postresult = Article.objects.filter(title__contains=query)
          result = postresult
       else:
           result = None
       return result

In your template to search query,

<form class="add_your_class" method="GET" action="" >
    <input class="add_your_class" type="search" name="search"> 
    <button class="add_your_class" type="submit"> Search </button>
</form>

In templates you can add it as to show results

{% for result in all_search_results %}
   {{ .....add according to your model }}
{% empty %}
   add something to show no results
{% endfor %}
like image 113
Bidhan Majhi Avatar answered Nov 15 '22 06:11

Bidhan Majhi