How to add Search bar for django template?

怎甘沉沦 提交于 2020-01-16 19:18:29

问题


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.


回答1:


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 %}


来源:https://stackoverflow.com/questions/57534404/how-to-add-search-bar-for-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!