How to execute jQuery ajax in real time to search for models in Django?

I tried to do a direct search with jquery and ajax and even posted a question regarding this here , but it looks like I have some serious problem somewhere in my view or in ajax script I wrote. It searches and downloads content correctly.

But if I step over and there is no value in the search form, it will still show me a list of values ​​that I entered for the first time. I think there is really a big problem in my code.

models.py:

class Status(models.Model): status = models.TextField() image = models.ImageField(upload_to=get_upload_file_name, blank=True) pub_date = models.DateTimeField(default=datetime.now) creator = models.ForeignKey(User, related_name="creator_set") likes = models.ManyToManyField(User, through="Like") 

fragment of the .html file:

  <input type="text" id="search" name="search" /> <ul id="search-results"> </ul> 

views.py:

 def search_status(request): if request.method == "GET": search_text = request.GET['search_text'] if search_text is not None and search_text != u"": search_text = request.GET['search_text'] else: search_text = '' # I even tried using 0 statuss = Status.objects.filter(status__contains = search_text) return render(request, 'ajax_search.html', {'statuss':statuss}) 

I already loaded the jquery.min.js script into my template.

+5
source share
1 answer

I had to defer the else statement and the return statement in view.py. And also put statuss in the second if statement. And then it worked, as I expected! Please guide me if there are any improvements. Thanks!

views.py:

 def search_status(request): if request.method == "GET": search_text = request.GET['search_text'] if search_text is not None and search_text != u"": search_text = request.GET['search_text'] statuss = Status.objects.filter(status__contains = search_text) else: statuss = [] return render(request, 'ajax_search.html', {'statuss':statuss}) 

This was an ajax script:

 $(function() { $('#search').keyup(function() { $.ajax({ type: "GET", url: "/status/search_status/", data: { 'search_text' : $('#search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data) } 

Snippet index.html:

  <input type="text" id="search" name="search" /> <ul id="search-results"> </ul> 

Html included:

 {% if statuss > 0 %} <ul class="statuss"> {% for status in statuss %} <li> <p>{{status}}</p> </li> {% endfor %} </ul> {% else %} <p>No status found.</p> {% endif %} 
+7
source

Source: https://habr.com/ru/post/1501676/


All Articles