如何在Django中创建按钮过滤器,而无需重新加载页面?

时间:2019-05-01 05:28:15

标签: python ajax django

我得到一个包含书籍的列表,我必须创建过滤器按钮进行分类,现在每单击一次按钮,我就会在链接“ ?filter = 2 ”中传递参数。但这需要重新加载页面。

    In the get function 
    self.book_type = request.GET.get("book_type")

    in the get_queryset
    return qs.filter(book_filter=self.book_type)

    HTML
    Simply redirecting to the page with a query added to the link 
    containing ?book_type=" anything"

1 个答案:

答案 0 :(得分:0)

您必须拥有这样的视图:

from django.http import JsonResponse

def get_books(request):
    book_type = request.GET.get("book_type")
    res = qs.filter(book_filter=self.book_type)
    return JsonResponse({"data": res})

然后像这样在模板中创建url(它会创建一个包含get_books网址的javascript变量):

<script> book_get_url = "{% url 'route_name_to_get_books_from_urls.py' %}";</script>

现在您可以像这样在JavaScript中使用book_get_url变量:

$.ajax({
    url: book_get_url,
    type: "GET",
    "data": {
         book_type: here is your book_type as a number
    },
    success: function (data) {
        //here you have your books in `data.data` in json fromat
    }
)};