Reputation: 3749
Search field in Django Template
How to create search field in Django Template similar to this image
http://asciicasts.com/system/photos/1204/original/E354I01.png
I try this in github https://github.com/rg3915/vendas/commit/e0c67fd8154a3b8e450ec3db38705cdd7efc1350
But i do not know how to finish.
Upvotes: 3
Views: 38164
Reputation: 31
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')
Upvotes: 3
Reputation: 10553
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 areaction='/other/url/'
<-- This tells django to do the GET in that URLurls.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:
Upvotes: 23