[Django]-Search field in Django Template

23👍

You’re talking about search field but essentially is just a form, you have an input (the search box) and you receive that input in your view.

Little example to manage forms and GET actions:

views.py:

def your_view(request):
    ''' This could be your actual view or a new one '''
    # Your code
    if request.method == 'GET': # If the form is submitted

        search_query = request.GET.get('search_box', None)
        # Do whatever you need with the word the user looked for

    # Your code

template

In your template, the most important thing for this is the form, you should have something like this:

# Your template code
<form type="get" action="." style="margin: 0">
    <input  id="search_box" type="text" name="search_box"  placeholder="Search..." >
    <button id="search_submit" type="submit" >Submit</button>
</form>
# Your template code
  • action='.' <– This tells django to do the GET action in the same URL as you are
  • action='/other/url/' <– This tells django to do the GET in that URL
  • This form is just an HTML form, you can use also Django Forms

urls.py

Your URL file has to be the same you had before. You don’t need to do any change to your actual URL, it should be something like:

url(r'^your_url/?$', 'yourproject.views.your_view', name='your_url_name'),

Anyway I recommend you to check some information like:

3👍

Frontend: Template

create a form with a search box(using html ,css)

<form type="get" action="exact_url" > 
    <input  id="search_box" type="text" name="search_box"  placeholder="Search..." > 
    <button id="search_submit" type="submit" >Submit</button> 
</form> 

Backend: View

  • write a funtion in views.py

  • Search | Django documentation | Django (https://docs.djangoproject.com/en/3.1/topics/db/search/#search) use it writing query

  • the jsonresponse can be rendered using template language Templates | Django documentation | Django (https://docs.djangoproject.com/en/3.1/topics/templates/#the-django-template-language)

  • write a query using __contains

       def your_view(request):
          if request.method == GET:  
              search_text = request.GET.get(search_box", None)
              records=Table.objects.filter(columnn__contains=search_text)     
              from django.http import JsonResponse
              return JsonResponse({"result_records":records})
    
  • your url should be same as in **form(template) **and your_view should be same as in views.py (View)

       url(r'^exact_url/?$', 'yourproject.views.your_view')
    

Leave a comment