使用Ajax过滤和更新Django ListView中的queryset表

时间:2018-07-19 00:00:18

标签: django-templates

我在通过Ajax向ListView发送数据时遇到问题。问题是我有一个搜索表单和一个选择来过滤搜索,后者在表单之外。我可以很好地发送数据,但是我不知道如何在我的视图中更新表的DOM或执行该操作的方法。接下来,我通过我的代码。

view.py

print

main.js

from django.shortcuts import render
from django.db.models import Q
from django.views.generic import ListView
from django.contrib.auth.mixins import LoginRequiredMixin
from app.catalog.models import (Product, Brand)


class ProductList(LoginRequiredMixin, ListView):
    login_url = '/accounts/login/'
    model = Product
    context_object_name = 'products'
    paginate_by = 15

    def get_context_data(self, **kwargs):
        context = super(ProductList, self).get_context_data(**kwargs)
        context['brands'] = Brand.objects.all()
        return context

    def get_queryset(self):
        import pprint
        products = Product.objects.get_active()
        try:
            q = self.request.GET['q']
            if q:
                products = products.filter(
                    Q(code__icontains=q) | Q(name__icontains=q) |
                    Q(brand__name__icontains=q) |
                    Q(aplication__name__icontains=q)
                )
        except KeyError:
            pass
        if self.request.is_ajax():
            pprint.pprint(self.request.GET)
            try:
                brand_id = self.request.GET['b']
                if brand_id:
                    products = products.filter(brand__pk=brand_id)
            except KeyError:
                pass

        return products

product_list.html

// send_brand
function send_brand() {
    console.log("send_brand is working!") // sanity check
    console.log("PK "+$('#brand').val()+" "+"Text "+$('#brand option:selected').text())
    $.ajax({
        url : "/{% if request.GET.q}?q={{ request.GET.urlencode }}{% endif %}", // the endpoint
        type : "GET", // http method
        data : { b : $('#brand').val() }, // data sent with the post request

        // handle a successful response
        success : function(data) {
            //$('#post-text').val(''); // remove the value from the input
            console.log(data); // log the returned json to the console
            console.log("success"); // another sanity check
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            //$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                //" <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });

};
// Event over select brand
$('#brand').on('change', function(){
    send_brand();
});

我在等待您的答复,非常感谢您。

0 个答案:

没有答案