Django — Как фильтровать базу данных с помощью тега выбора HTML?

#django #filter #drop-down-menu

#django #Фильтр #выпадающее меню

Вопрос:

Я пытаюсь создать веб-сайт электронной коммерции. Итак, я пытаюсь добавить фильтры типа Цена: низкая — Высокая и наоборот. Я знаю, как фильтровать цену, но я не знаю, как применить фильтр при изменении значения выбора.

Вот HTML-код

  <div class="d-flex flex-row-reverse" style="margin-right: 20px; margin-bottom: 20px;">
    <label>
        <select class="bg-dark" name="price" id="priceFilter">
            <option value="normal">Sort by Price</option>
            <option value="low">Low-to-High</option>
            <option value="high">High-to-Low</option>
        </select>
    </label>
</div>
 

Код Django

 def index(request):
    fil = request.GET('price')
    if fil == "low":
        products = Product.objects.all().order_by('productDiscountedPrice')
    elif fil == "high":
        products = Product.objects.all().order_by('-productDiscountedPrice')
    else:
        products = Product.objects.all()
    context = {
        'products': products
    }
    return render(request, "Amazon/index.html", context)
 

Итак, как сортировать продукты при select tag изменении значения?

Ответ №1:

  • Вам нужно использовать ajax, если вы не хотите перезагружать страницу. Вот ссылка на учебник ajax.
  • Включите эту <a rel=»noreferrer noopener nofollow» href=»https:///» rel=»nofollow noreferrer»>ссылку jquery в главный тег заголовка HTML-страницы.
          <script>
             $('#priceFilter').on('change', 'input, select', function(event){
             // id = this.id; // you can use this.id to get the corresponding id.
    
                 var word = $("#priceFilter").val();
    
                 $.ajax({ 
                     type: 'GET',
                     url: '{% url <YOUR DJANGO INDEX VIEW URL NAME> %}',
                     data: {
                         word: word,
                     },
                     success: function (response) { 
                         console.log(response); // print response.content and response.data to see the data in the console. And later you can use those data in template using javascript.
                     },
                     error: function (error_data) {
                         console.log(error_data)
                     }
                 });
    
            }
         </script>
     

И в views.py , напишите изменить свой взгляд следующим образом:

 from django.shortcuts import render
from django.http import JsonResponse

def index(request):
    fil = request.GET('price')
    if fil:
        if fil == "low":
            products = Product.objects.all().order_by('productDiscountedPrice')
        elif fil == "high":
            products = Product.objects.all().order_by('-productDiscountedPrice')
        else:
            products = Product.objects.all()
        context = {
            'products': products
        }
        return JsonResponse(context)
    else:
        context = {}
        return render(request, "Amazon/index.html", context)