Reputation:
I'm not familiar with jquery and I'm creating a project using Django. Now I am trying to create a search function. What I want to do is showing up entries that have a specific word the user input without loading the page.
I'm not sure what this page is using but what I want to create is basically like this page.
https://simpleisbetterthancomplex.com/search/
But I don't understand how I can adapt ajax into Django yet, anyone who can give me an example and tips?
Upvotes: 0
Views: 1054
Reputation: 108
As pissall already mentioned taking a course is surely useful. However, what you are looking for is this:
Define the jQuery Link in your Base template first. Let's assume your search looks like this:
<form id="search" method="get" action="">
<input type="text" id="id_q" name="q"/>
<button type="submit">Search</button>
</form>
Now you need to fetch the data entered in the form. Put this into your JS File that you have already linked in your base template:
$("#id_q").change(function () {
$.ajax({
url: "/search/", //Replace this with your search URL
type: "get", // Querying means getting in HTTP terms
data: $("#search").serialize(), // This transforms your search form into a JSON dictionary.
success: function (data){...}, // Do sth here.
error: function (xHR, textStatus) {...} // Handle server-side errors here.
});
})
Note that this is a rudimental AJAX GET request that you can use as a basis for your search. The data
is sent to Django looks like this: {'q': 'Whatever you're searching for'}
.
In your Django View you can take the q from the request:
# Imports
from Django.http import JsonResponse
def search_func(request):
if request.GET.get('q'):
q = request.GET.get('q')
model = YourModel.objects.filter(name__icontains=q)
return JsonResponse(data={'results': model})
else:
# Handle empty queries
The JSON Response returns a serialized dictionary that looks like the dict you have passed to the data
attribute of JsonResponse. Within the jQuery function defined above you can access the 'results'
with in the success
key of the AJAX function as follows:
$("#id_q").change(function () {
$.ajax({
url: "/search/", //Replace this with your search URL
type: "get", // Querying means getting in HTTP terms
data: $("#search").serialize(), // This transforms your search form into a JSON dictionary.
success: function (data){
example = data.results // That's where you get your query results.
// Handle your results
}, // Do sth here.
error: function (xHR, textStatus) {...} // Handle server-side errors here.
});
})
Hope that helps you a little bit.
Upvotes: 1