Aman Bhatnagar
Aman Bhatnagar

Reputation: 67

How to add Search bar for django template?

I need a search bar in my template on top of my table. The search bar should search based on any table parameter, and filter the enteries accordingly.

I implemented the search bar using CSS classes and I get it as I wanted. Now here's the views.py code.

def jobs(request):
    jobs = Jobb.objects.all()
    search_term = ''
    if 'search' in request.GET:
        search_term = request.GET['search']
        jobs = jobs.filter(position__icontains=search_term)
    context = {
        'jobs': jobs, 'search_term': search_term, 'job': 'active'
    }
    return render(request, 'Job_openings/jobb.html',context)

This code does the job for me , but the problem is that it only searches the enteries based on my model return value.

def __str__(self):
    return self.position

Thus, I'm only able to search all enteries having some specific 'position'.

My model has other fields like 'date posted', 'company name'.. I want the search bar to work for all such fields. Lets say I enter a company name, and I get all the results from the list.

How can I achieve this? Thanks in advance.

Upvotes: 1

Views: 503

Answers (1)

lieahau
lieahau

Reputation: 518

you can use Q objects to perform "OR" queries.

from django.db.models import Q


jobs = jobs.filter(
    Q(position__icontains=search_term) |
    Q(your_other_field__icontains=search_term) |
    Q(....)
)

then, in your template, you can access it with loop, and use dot "." to access the fields like:

{% for job_item in jobs %}
    {{ job_item.position }}, {{ job_item.your_other_field }}
{% endfor %}

Upvotes: 1

Related Questions