django 我正在尝试从GET请求中排除不包含值的参数

mec1mxoz  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(156)

我有这个代码在search.html

<h1>Property Search</h1>
    <hr>
    <form method="GET" action="/search/results/?{{ query_params }}" class="form-inline" style="display: flex; justify-content: center; align-items: center; ">
        <div class="form-group mx-sm-3 mb-2">
            <label for="inputSaleRent" class="mr-2" style="margin-right: 10px; font-weight: bold;">Sale/Rent:</label>
            <select id="inputSaleRent" name="sale_rent" class="form-control" style="width: 150px; margin-right: 10px;">
                <option value="">Choose...</option>
                <option value="sale">For Sale</option>
                <option value="rent">For Rent</option>
            </select>
        </div>
        <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;">
            <label for="inputDistrict" class="mr-2" style="margin-right: 10px; font-weight: bold;">District:</label>
            <select id="inputDistrict" name="district" class="form-control" style="width: 150px; margin-right: 10px;">
                <option value="">Choose...</option>
                <option value="District 1">District 1</option>
                <option value="District 2">District 2</option>
                <!-- Add more district options -->
            </select>
        </div>
        <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;">
            <label for="inputMunicipality" class="mr-2" style="margin-right: 10px; font-weight: bold;">Municipality/Community:</label>
            <select id="inputMunicipality" name="municipality" class="form-control" style="width: 150px; margin-right: 10px;">
                <option value="">Choose...</option>
                <option value="Municipality 1">Municipality 1</option>
                <option value="Municipality 2">Municipality 2</option>
                <!-- Add more municipality options -->
            </select>
        </div>
        <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;">
            <label for="inputParish" class="mr-2" style="margin-right: 10px; font-weight: bold;">Parish:</label>
            <select id="inputParish" name="parish" class="form-control" style="width: 150px; margin-right: 10px;">
                <option value="">Choose...</option>
                <option value="Parish 1">Parish 1</option>
                <option value="Parish 2">Parish 2</option>
                <!-- Add more parish options -->
            </select>
        </div>
        <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;">
            <label for="inputPropertyType" class="mr-2" style="margin-right: 10px; font-weight: bold;">Property Type:</label>
            <select id="inputPropertyType" name="property_type" class="form-control" style="width: 150px; margin-right: 10px;">
                <option value="">Choose...</option>
                <option value="Apartment">Apartment</option>
                <option value="Studio">Studio</option>
                <!-- Add more property type options -->
            </select>
        </div>
        <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;">
            <label for="inputMinPrice" class="mr-2" style="margin-right: 10px; font-weight: bold;">Min Price:</label>
            <input type="text" name="min_price" class="form-control" id="inputMinPrice" style="width: 150px; margin-right: 10px;">
        </div>
        <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;">
            <label for="inputMaxPrice" class="mr-2" style="margin-right: 10px; font-weight: bold;">Max Price:</label>
            <input type="text" name="max_price" class="form-control" id="inputMaxPrice" style="width: 150px; margin-right: 10px;">
        </div>
        <button type="submit" class="btn btn-primary mb-2" style="display: flex; align-items: center; margin-left: 10px;">Search</button>
    </form>
    <hr>

基本上,用户在搜索栏中输入感兴趣的值,并且通过按下搜索,它检索与值匹配的属性,但是如果它仅在用户应用搜索的所有值时才起作用。
我的www.example.com也vies.py是这样的

def property_search(request):
if request.method == 'GET':
return render(request, 'search.html')

    if request.method == 'POST':
        sale_rent = request.POST.get('sale_rent')
        district = request.POST.get('district')
        municipality = request.POST.get('municipality')
        parish = request.POST.get('parish')
        property_type = request.POST.get('property_type')
        min_price = request.POST.get('min_price')
        max_price = request.POST.get('max_price')
    
        query_params = {}
    
        # Set the query parameters based on the provided values
        if sale_rent:
            query_params['sale_rent'] = sale_rent
        if district:
            query_params['district'] = district
        if municipality:
            query_params['municipality'] = municipality
        if parish:
            query_params['parish'] = parish
        if property_type:
            query_params['property_type'] = property_type
        if min_price:
            query_params['min_price'] = min_price
        if max_price:
            query_params['max_price'] = max_price
    
        properties = Property.objects.all()
    
        # Apply filters based on the search criteria
        if sale_rent:
            properties = properties.filter(sale_rent=sale_rent)
        if district:
            properties = properties.filter(district=district)
        if municipality:
            properties = properties.filter(municipality=municipality)
        if parish:
            properties = properties.filter(parish=parish)
        if property_type:
            properties = properties.filter(property_type=property_type)
        if min_price:
            properties = properties.filter(price__gte=min_price)
        if max_price:
            properties = properties.filter(price__lte=max_price)
    
        # Generate the URL query string without empty parameters
        encoded_query_params = urlencode(query_params)
    
        context = {'properties': properties, 'query_params': encoded_query_params}
        return render(request, 'property_search_results.html', context)
    
    return render(request, 'search.html')

在我按下搜索后获取请求看起来像这样
GET /search/results/?sale_rent=sale&district=&municipality=&parish=&property_type=&min_price=1000&max_price=1000000000
范围是如果用户不应用任何值并按下搜索所有要检索的属性,如果用户只选择销售_rent并放置sale所有要检索的销售属性,则当前情况并非如此

s5a0g9ez

s5a0g9ez1#

范围是如果用户不应用任何值并按下搜索所有要检索的属性,以及如果用户只选择销售_rent并放置sale所有要检索的销售属性,这不是现在正在进行的情况。
主要原因是您使用request.POST处理此操作,实际上您检查是否为request.method == 'POST',无论如何都会失败。
但是您在这里使用了太多的样板代码。您可以使用django-filter package [GitHub]提供的简单过滤器。首先我们定义一个过滤器:

import django_filters

class PropertyFilter(django_filters.FilterSet):
    min_price = NumberFilter(field_name='price', lookup_expr='gte')
    max_price = NumberFilter(field_name='price', lookup_expr='lte')

    class Meta:
        model = Property
        fields = (
            'sale_rent',
            'district',
            'municipality',
            'parish',
            'property_type',
        )

然后我们可以在视图中使用以下内容进行过滤:

def property_search(request):
    _filter = ProductFilter(request.GET, queryset=Property.objects.all())
    encoded_query_params = urlencode(
        {
            k: request.GET[k]
            for k in (
                'sale_rent',
                'district',
                'municipality',
                'parish',
                'property_type',
                'min_price',
                'max_price',
            )
            if k in request.GET
        }
    )

    context = {'properties': _filter.qs, 'query_params': encoded_query_params}
    return render(request, 'property_search_results.html', context)

这里,过滤器将因此查看该项目是否在request.GET字典中,并且如果是,则相应地过滤查询集。

相关问题