如何在Django中使用Ajax对列表视图进行排序?

2024-05-07 18:37:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在列表视图模板中,我创建了一个过滤表单,用于过滤帖子,同样,它们是一个排序下拉列表,用于对帖子进行排序:

<form id="sortForm">
    <select class="input-text" id="sort" onchange="document.querySelector('#sortSubmitBtn').click()" name="sort"
        id="sort">
        <option disabled selected>Sort by</option>
        <option value="price_l2h" {% if 'price_l2h' == values.sort %} selected {% endif %}>
            Price (low to high)</option>
        <option value="price_h2l" {% if 'price_h2l' == values.sort %} selected {% endif %}>
            Price (high to low)</option>
    </select>
    {% if values.keywords %}
    <input type="hidden" name="keywords" id="keywords" value="{{ values.keywords }}">
    {% endif %}
    {% if values.mls_number %}
    <input type="hidden" name="mls_number" id="mls_number" value="{{ values.mls_number }}">
    {% endif %}

    <button type="submit" id="sortSubmitBtn" style="display: none;">Submit</button>
</form>

这是我用来排序的Ajax,但它不起作用。我使用相同的Ajax语法在模型中保存数据,它工作得很好,但这个不起作用

<script>
    $(document).on('submit', '#sortForm', function (e) {
        e.preventDefault();

        $.ajax({
            type: 'GET',
            url: "{% url 'listing:search' %}",
            data: {
                sort: $('#sort').val(),
                keywords: $('#keywords').val(),
                mls_number: $('#mls_number').val(),
                csrfmiddlewaretoken: "{{ csrf_token }}",
            },
            success: function () {
                alert('Form submitted successfully!!');
            }
        })
    })

</script>

urls.py

path('search/', search, name='search'),

谢谢,我希望有人能帮我

编辑:这是GUI的外观,在选择“我希望它对列表进行排序”时:

enter image description here

编辑:添加了views.py

def search(request):
    queryset = Listing.objects.all().order_by('listing_date')

    listing_for = request.GET.get('listing_for')

    # filter by price
    min_price = request.GET.get('min_price')
    max_price = request.GET.get('max_price')
    if min_price and max_price:
        queryset = queryset.filter(price__range=(min_price, max_price))

    # Filter by new mls number
    mls_number = request.GET.get('mls_number')
    if mls_number:
        queryset = queryset.filter(mls_number__exact=mls_number)

    # filter by keyword
    keywords = request.GET.get('keywords')
    if keywords:
        queryset = queryset.filter(Q(description__icontains=keywords) | Q(
            lot_feature__title__icontains=keywords) | Q(interior_feature__title__icontains=keywords) | Q(exterior_finish__title__icontains=keywords) | Q(extra_feature__title__icontains=keywords) | Q(appliances__title__icontains=keywords) | Q(view__title__icontains=keywords)).distinct()

    # sorting function
    sort_by = request.GET.get('sort')
    if sort_by:
        if sort_by == 'price_l2h':
            queryset = queryset.order_by('price')
        elif sort_by == 'price_h2l':
            queryset = queryset.order_by('-price')
        elif sort_by == 'newest':
            queryset = queryset.order_by('-listing_date')
        elif sort_by == 'bedrooms':
            queryset = queryset.order_by('-bedrooms')
        elif sort_by == 'bathrooms':
            queryset = queryset.order_by('-bathrooms')
        elif sort_by == 'sqrft':
            queryset = queryset.order_by('-sqrft')

    context = {
        'listings': queryset,
        'city': city,
        'provinces': provinces,
        'prices': prices,
        'property_types': property_type,
        'rooms': rooms,
        'values': request.GET,
        'int_values': int_values,
        'page': page,
    }

    return render(request, 'listing/listings.html', context)

Tags: idnumbergetbyifrequestordersort
2条回答

这不是ajax的工作方式,您需要发送JsonResponse并对其进行操作。对于这种操作,您可以使用django-rest-framework,这将使您的工作更简单。如果你不想使用它,你必须修改你的代码如下 link.

为了在服务器端对数据进行排序,可以使用QuerySet的order_by-方法或模型的ordering-元选项

您还可以在客户端用JavaScript对返回的数据进行排序

相关问题 更多 >