Home > database >  How to pass search input value in output
How to pass search input value in output

Time:11-21

I have search bar that renders the list of elements that user whats to find. I'd like to pass the input value to output html so if user is searching for article 1 then I want to display above the list the query name. I tried to put query, lookup but it doesn't work.

views.py

def search_qa_results(request):
query = request.GET.get('q')
qa_list = QA.objects.filter(title__icontains=query)
if query is not None:
    lookups = Q(title__icontains=query)
    qa_list = QA.objects.filter(lookups)
context = {
    'qa_list': qa_list
}
return render(request, 'search/search_qa.html', context)

index.html

<form action="{% url 'search_qa_results' %}" method="get" id="search">
  {% csrf_token %}
  <div class="searchbar" id="autocomplete">
    <input name="q" type="text" placeholder="Type your question" class="search_input">
    <a href="{% url 'search_qa_results' %}" class="search_icon"><i class="fas fa-search"></i></a>
    <ul class="autocomplete-result-list"></ul>
  </div>
</form>

search_results.html

{% extends 'base.html' %}
<title>{% block title %}Q&A results{% endblock %}</title>

{% block content %}
<link rel="stylesheet" type="text/css" href="/static/search_qa.css">
<div class="d-flex justify-content-start"> Search results for my question: {{WHAT TO PUT HERE?}}</div>
<div class="container h-100 pb-4">
    <div class="d-flex justify-content-end h-100 pb-4">

    {% for qa in qa_list %}
    <div class="card text-dark bg-light mb-3 text-left">
    <a href="{{ qa.get_absolute_url }}">
        <h5 class="card-header">Q: {{qa.title}}</h5>
        <div class="card-body">
            <div class="card-title text-justify">A: {{ qa.answer }}</div>
        </div>
        <div class="card-footer">
            <small class="text-muted">Published: {{qa.publish}}</small>
        </div>
        </a>
    </div>
    {% empty %}
    <p>No results</p>
    {% endfor %}
</div>

CodePudding user response:

If you only want to display the query name, you simply need to add it to on the context :

views.py

def search_qa_results(request):
    context = {}
    query = request.GET.get('q', None)
    if query:
        lookups = Q(title__icontains=query)
        qa_list = QA.objects.filter(lookups)
        context = {
            'qa_list': qa_list,
            'query_name': query
        }
    else:
        # Return all the objects as default if query name is empty
        context = {
            'qa_list': QA.objects.all()
        }
    return render(request, 'search/search_qa.html', context)
        

search_qa.html

{% if query_name %}
<div class="d-flex justify-content-start"> Search results for {{ query_name }}</div>
{% else %}
<div class="d-flex justify-content-start"> Please enter something in the search bar</div>
{% endif %}
  • Related