Django Ajax search will not work

两盒软妹~` 提交于 2019-12-12 01:58:33

问题


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 is wrong. Whenever I search, for a document it always returns No Documents available!! instead of the documents I'm searching for.

Heres the view for it:

 def search(request):

      if request.method == 'POST':    
           search_text = request.POST['search_text']

      else:
           search_text = ''

      if search_text:
           documents = Document.objects.filter(document_subject__contains=search_text,           approved=True)

      else:
           documents = False

   return render(request,'ajax_search.html',{'documents':documents})

This is my ajax_search template:

 {% if documents.count > 0 %}

 {% for document in documents %}
 <li><a href="/main/get/{{ document.id }}/">{{ document.document_subject }}</a></li>
 {% endfor %}

 {% else %}

 <li> None to show!!</li>

 {% endif %}

My ajax file:

$(function (){

    $('#search').keyup(function(){

        $.ajax({
            type: 'POST',
            url: '/main/search/',
            data: {
                'search_text' : $('#search').val(),
                'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });

    });

});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
}

This is in my base.html file:

 <script type="text/javascript" src="{{ STATIC_URL }} /static/jquery-2.1.1.min.js">   </script>
 <script type="text/javascript" src="{{ STATIC_URL }} /static/ajax.js"></script>

My document model:

class Document(models.Model):

    docfile = models.FileField(upload_to='documents/%Y/%m/%d')
    document_subject = models.CharField(max_length=255)
    document_subject_number = models.PositiveIntegerField(max_length=999)

    def __unicode__(self):
      return self.document_subject

    def get_absolute_url(self):
      return "/main/get/%i/" %self.id

If you have any other questions just let me know thanks in advance, I'm new to python and django so I appreciate any feed back. Thanks in advances

Search Part of the template:

<ul>
  <li><a href='/documents/all'>Documents</a></li>
  <li><a href='documents/create'>Create Documents</a></li>
</ul>
<h3>Search</h3>
{% csrf_token %}
<input type ='text' id="search" name="search"/>
<ul id="search-results">

</ul>

回答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.

def search(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:
            pass

    return 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><a href="/main/get/{{ document.id }}/">{{ document.document_subject }}</a></li>
    {% endfor %}

 {% else %}
    <li> None to show!!</li>
 {% endif %}


来源:https://stackoverflow.com/questions/25290043/django-ajax-search-will-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!