Created
June 5, 2015 14:04
-
-
Save pvgdevelop/1c033a56e8172e960872 to your computer and use it in GitHub Desktop.
Django Ajax search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
$(function(){ | |
$('#search').on('keyup', function(){ | |
var _this = $(this), | |
found = $('#main-search-found'); | |
if (_this.val().length >= 3) { | |
$.ajax({ | |
type: "POST", | |
url: "/search/", | |
data: { | |
'search_query': $('#search').val(), | |
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val() | |
}, | |
dataType: 'html', | |
success: function(data){ | |
found.html(data).slideDown(); | |
console.log(data); | |
} | |
}); | |
} else { | |
found.slideUp(); | |
} | |
}).on('focusout', function(){ | |
$('#main-search-found').slideUp(); | |
}).on('focus', function(){ | |
if ($(this).val().length >= 3) { | |
$('#main-search-found').slideDown(); | |
} | |
}); | |
}); | |
</script> | |
{% csrf_token %} | |
<input name="search" id="search"> | |
<div id="main-search-found"> | |
<!-- here the search result is paste --> | |
</div> | |
############################### | |
urls.py | |
... | |
url(r'^search/$', views.search_product, name='search_product'), | |
... | |
############################### | |
search_result.html | |
{% load i18n thumbnail %} | |
{% if products.count > 0 %} | |
{% for product in products %} | |
<a href="{{ product.get_absolute_url }}">{{ product.title }}</a> | |
{% endfor %} | |
{% endif %} | |
############################### | |
views.py | |
def search_product(request): | |
if request.method == 'POST': | |
search_query = request.POST['search_query'] | |
else: | |
search_query = '' | |
# Look in Porduct title, short and full descriptions, Category title and parent Category title | |
products = Product.objects.filter(Q(title__icontains=search_query) | | |
Q(short_description__icontains=search_query)) | |
content = {} | |
content.update(csrf(request)) # put it in the view function where the input field is rendered | |
content['products'] = products | |
return render(request, 'partials/search_result.html', content) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment