Django Ajax Search Will Not Work
I've been following this tutorial: https://www.youtube.com/watch?v=jKSNciGr8kY I am just completely stuck, I have gone through my code line by line and still cannot figure out what
Solution 1:
You are only fetching Data, there is no reason to use POST, just use GET.
$(function (){
$('#search').keyup(function(){
$.ajax({
type: 'GET',
url: '/main/search/',
data: {search_text:$('#search').val()},
success: function(newData) {
$('#search-results').html(newData);
}
});
});
});
EDIT: you filter on approved in your question, yet I see no approved field in your model. I have removed approved from the filtering in the bellow view to follow your model Refactored your view, no need for so many lines of code.
defsearch(request):
documents = None"""
request.GET.get will always return the value of the key if set or None (you can alternatively specify a default return value).
"""
search_text = request.GET.get('search_text')
if search_text :
"""
Use some try, catch we don't need the server to fail because of a search action...
"""try:
documents = Document.objects.filter(document_subject__contains=search_text)
except:
passreturn render(request, 'ajax_search_html',{'documents':documents})
In the view you could add: if request.is_ajax()
to check if this is an ajax request, but since your view feels acting the same ajax or not I see no reason.
The template:
{% if documents %}
{% for document in documents %}
<li><ahref="/main/get/{{ document.id }}/">{{ document.document_subject }}</a></li>
{% endfor %}
{% else %}
<li> None to show!!</li>
{% endif %}
Post a Comment for "Django Ajax Search Will Not Work"