Avishka Dambawinna
Avishka Dambawinna

Reputation: 1215

Django-filter field not showing after adding lookup expressions - django-filter lib

I'm trying to implement a search field for my website, I decide to use django-filter

I was able to create a search field and search the records by typing the exact record name in the search field. (default it provides exact field lookup) And it worked fine. before

Then I decide to add more field lookup so the search experience improves. But after adding some field lookups the search form field stopped appearing in the template. enter image description here

I go through the documentation couple of times and also tried to google the issue but unable to solve it.

Test: By the way, hard cording the field lookups(icontains) to the queryset worked. And also the query set works fine.

So here's my context processor which handles the search field(search field is in the base.html)

context_processor.py

from django.db.models import Prefetch
from django.shortcuts import render
from store.filters import ProductFilter
from store.models import Product, ProductImage, Wishlist


def include_search_bar(request):
    queryset = Product.objects.order_by('name').prefetch_related(
        Prefetch(
            'productimage_set',
            ProductImage.objects.filter(place='Main Product Image'),
            to_attr='main_image'
        ),
    )
    product_filter = ProductFilter(request.GET, queryset=queryset)
    products = product_filter.qs

    context = {
        'product_filter': product_filter,
        'products': products,
    }

    return context
    

filters.py

import django_filters from .models import Product

class ProductFilter(django_filters.FilterSet):
    class Meta:
        model = Product
        fields = {  
            'name':['icontains']
        }
        # fields = ['name'] worked fine

base.html

<form class="form-inline d-flex active-pink md-form form-sm mr-3" method="get" id="search">
    <div class="input-group">
        {% render_field product_filter.form.name class="form-control form-control-sm" %}
        <div class="input-group-prepend">
            <button type="submit" class="input-group-text btn fa fa-search" id="inputGroupPrepend2"></button>
        </div>
    </div>
</form>

Upvotes: 1

Views: 678

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

With 'name': ['icontains'], you filter with name__icontains, so the name of the search field (in the HTML form) should be name__icontains:

{% render_field product_filter.form.name__icontains class="form-control form-control-sm" %}

Upvotes: 1

Related Questions