Prusa
Prusa

Reputation: 179

How to display search term on search results page in django?

I made a form and then i made little search form and it works but, i didnt display the search term on the search results page...

I just wanna show Search Results for (Search Term) enter image description here

Here are my codes.

Views.py

   class SearchResultsView(ListView):
    model = Post
    template_name = 'search.html'

    def get_queryset(self): 
        query = self.request.GET.get('q')
        object_list = Post.objects.filter(Q(soru1__icontains=query) | Q(soru2__icontains=query) |
        Q(soru3__icontains=query) |
        Q(soru4__icontains=query) |
 )
        return object_list 

      

Base.html ( search bar in it)

<form class="d-flex" action="{% url 'search' %}" method="get">
<input class="form-control me-2" name="q" type="text" placeholder="Arama..."> 
<button class="btn btn-outline-success" type="submit">Ara</button></form>

And search.html

{% extends 'base.html' %}

{% block content %}


    <h1>Search Results for </h1>

    <ul>
      {% for Post in object_list  %}
        <li>
           <a href="{% url 'article-detail' Post.id %}">{{ Post.soru1 }}</a>
        </li>
      {% endfor %}
    </ul>

{% endblock %}

Upvotes: 0

Views: 787

Answers (1)

Waldemar Podsiadło
Waldemar Podsiadło

Reputation: 1412

You need to add query to context:

Views.py

  class SearchResultsView(ListView):
    model = Post
    template_name = 'search.html'

    def get_queryset(self): 
        query = self.request.GET.get('q')
        object_list = Post.objects.filter(Q(soru1__icontains=query) | Q(soru2__icontains=query) |
        Q(soru3__icontains=query) |
        Q(soru4__icontains=query) )
        return object_list

    def get_context_data(self, **kwargs):
        context = super(SearchResultsView, self).get_context_data(**kwargs)
        context['query'] = self.request.GET.get('q')
        return context

and in template:

{% extends 'base.html' %}

{% block content %}


    <h1>Search Results for {{ query }} </h1>

    <ul>
      {% for Post in object_list  %}
        <li>
           <a href="{% url 'article-detail' Post.id %}">{{ Post.soru1 }}</a>
        </li>
      {% endfor %}
    </ul>

{% endblock %}

Upvotes: 1

Related Questions