Answer the question
In order to leave comments, you need to log in
Django-filters, why doesn't __init__ work in FilterSet?
Good afternoon. I am using django-filters, I want to override __init__ in FilterSet
# оба варианта не работают
class ProductFilter(django_filters.FilterSet):
def __init__(self, *args, **kwargs):
slug = kwargs.pop('slug', None)
super(ProductFilter, self).__init__(*args, **kwargs)
self.filters['brand'].extra.update({
'queryset': Brand.objects.filter(is_active=True,
product_brand__isnull=False,
product_brand__category__slug=slug),
'empty_label': '',
'help_text': False
})
# self.brand = django_filters.ModelMultipleChoiceFilter(field_name='brand__name', to_field_name='name',
# label='Бренды')
# self.brand.queryset = Brand.objects.filter(is_active=True, product_brand__isnull=False,
# product_brand__category__slug=slug)
class Meta:
model = Product
fields = ['brand']
class ProductFilter(django_filters.FilterSet):
brand = django_filters.ModelMultipleChoiceFilter(field_name='brand__name',
to_field_name='name',
label='Бренды',
queryset=Brand.objects.filter(is_active=True,
product_brand__isnull=False,
product_brand__category__slug='slug_category'),
widget=forms.CheckboxSelectMultiple)
class Meta:
model = Product
fields = ['brand']
Answer the question
In order to leave comments, you need to log in
This is how it should work
class ProductFilter(django_filters.FilterSet):
brand = django_filters.ModelMultipleChoiceFilter(field_name='brand__name',
to_field_name='name',
label='Бренды',
queryset=Brand.objects.all()
)
def __init__(self, *args, **kwargs):
slug = kwargs.pop('slug', None)
super(ProductFilter, self).__init__(*args, **kwargs)
self.filters['brand'].queryset = Brand.objects.filter(is_active=True,
product_brand__isnull=False,
product_brand__category__slug=slug),
widget=forms.CheckboxSelectMultiple)
class Meta:
model = Product
fields = ['brand']
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question