John B.
John B.

Reputation: 1

Search bar with Python-Django

i'm trying to build my first Django blog that someone can make an account, search & update posts and now i want to add a search bar so someone can find others by profile name. But i don't know how to make it exactly, i try to find something on google but nothing help me.

i try this: ( on the base.html )

<form type="get" action="/other/path/" style="margin: 0">
    <input  id="search_box" type="text" name="search_box"  placeholder="Search..." >
    <button id="search_submit" type="submit" >Submit</button>

( on the views.py )

@login_required
def search_bar(request):
    if request.method == 'GET':
        search_query = request.GET.get('search_box', None)

( on the urls.py )

path('', UserPostListView.as_view() , name='search'),

Upvotes: 0

Views: 815

Answers (1)

ItsMilann
ItsMilann

Reputation: 415

@login_required
def search_bar(request):
    if request.method == 'GET':
        search_query = request.GET.get('search_box', None)
        qs = YourModel.objects.filter(attribute__icontains = search_query)
        return render(request, 'search_results.html', {'results':qs})
        '''
        YourModel = Model where you want to run search
        attibute = attribute on your model where you want to run search
        search_results.html = is a seperate page where your search results will be displayed.
        '''

PS: This is just a basic example.

Upvotes: 1

Related Questions