Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

django filter using ajax

Problem when using ajax in django.

I use django-filter to sort products. When I use ajax for this, after selecting the category, the sorting operation is not done properly and it query again for all the products and returns the results if it should be only on the products related to the same category that I selected do this.

This is done correctly without using ajax. When I am not using ajax, after filtering the products, the url is as follows:

category/shoes/10/?brand=4/

But when I use ajax after filtering the url products as follows:

/category/shoes/10/

filter.py:

class ProductFilter(django_filters.FilterSet):
      brand = django_filters.ModelMultipleChoiceFilter(queryset=Brand.objects.all(), widget=forms.CheckboxSelectMultiple)

url:

 path('filter/', views.product_filter, name='filter')

views:

def product_filter(request, slug=None, id=None):
    products = Product.objects.all()
    category = Category.objects.filter(sub_cat=False)
    filter = ProductFilter(request.GET, queryset=products)
    products = filter.qs
    if slug and id:
        data = get_object_or_404(Category, slug=slug, id=id)
        products = products.filter(category=data)
    context = {'products': products, 'filter': filter,'category': category, }
    html = render_to_string('home/product-filter.html', context, request=request)
    return JsonResponse({'form': html})

template:

<form class="filter-form">
    <ul>
        <li class="list-group-item">
            <p>
                {{ filter.form.brand }}
            </p>
        </li>
    </ul>
    <button type="submit">filter</button>
</form>
    

ajax:

 <script>
    $(document).on('submit','.filter-form',function(event){
      event.preventDefault();
      $.ajax({
      type:'GET',
      url:'/filter/',
      data : $(this).serialize(),
      dataType: 'json',
      success: function (data) {
      console.log("success");
      $('#product-main').html(data['form']);
      },
      error: function (data) {
      alert("error " + data);
      }
      });
});
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...