Настройка начального фильтра выбора модели

#python #django #django-filters

Вопрос:

В настоящее время я пытаюсь установить начальный фильтр для своей категории на основе подкатегории, выбранной из моего домашнего шаблона.

index.html

 {% for category in Category_list %}  lt;div class="col-lg-3 offset-lg-0 col-md-5 offset-md-1 col-sm-6 col-6"gt;  lt;div class="category-block"gt;  lt;div class="header"gt;  lt;i class="fa fa-laptop icon-bg-1"gt;lt;/igt;   lt;h4gt;{{category}}lt;/h4gt;  lt;/divgt;  lt;form method="GET" action="{% url 'Product-search' %}"gt;  lt;ul class="category-list" gt;  {% for sub_cat in category.subcat.all %}  lt;ligt;  lt;button type="submit" class="subcat-button" name="subcategory" value={{ sub_cat.id }} gt;  {{sub_cat}}  lt;/buttongt;  lt;spangt;{{sub_cat.product.count}}lt;/spangt;  lt;/ligt;  {% endfor %}  lt;/ulgt;  lt;formgt;  lt;/divgt;  lt;/divgt; lt;!-- /Category List --gt;  {% endfor %}  

product-search.html У меня есть еще много фильтров на этой странице, но я пытаюсь просто задать параметры для filter.form.category для подкатегории, выбранной на главной странице.

 lt;div class="advance-search"gt;  lt;div class="form-row"gt;  lt;div class="form-group col-md-4"gt;  {{filter.form.q}}  lt;/divgt;  lt;div class="form-group col-md-3"gt;  {{filter.form.category}}  lt;/divgt;  lt;div class="form-group col-md-3"gt;  {{filter.form.city}}  lt;/divgt;  lt;div class="form-group col-md-2"gt;  lt;button type="submit" class="btn btn-primary"gt;Search Nowlt;/buttongt;  lt;/divgt;  lt;/divgt;  lt;/divgt;    

filters.py

 class ProductFilter(django_filters.FilterSet):   q = django_filters.CharFilter(widget=forms.TextInput(attrs={'class': 'form-control my-2 my-lg-0', 'id': "inputtext4", 'placeholder': 'What are you looking for'}),  method='my_custom_filter',  label="Search")  city = django_filters.CharFilter(widget=forms.TextInput(attrs={'class': 'form-control my-2 my-lg-0', 'id': "inputtext4", 'placeholder': 'City'}),  method='City_filter',  label="City")  Manufacturer = django_filters.CharFilter(widget=forms.TextInput(attrs={'class': 'form-control my-2 my-lg-0', 'id': "inputtext4", 'placeholder': 'Manufacturer'}),  method='Manufacturer_filter',  label="Manufacturer")  model = django_filters.CharFilter(widget=forms.TextInput(attrs={'class': 'form-control my-2 my-lg-0', 'id': "inputtext4", 'placeholder': 'Model'}),  method='Model_filter',  label="Model")   category = django_filters.ModelChoiceFilter(empty_label="Category", queryset=Category.objects.all(),  widget=forms.Select(  attrs={'class': "w-100 form-control mt-lg-1 mt-md-2", 'id': "inputCategory4"}),  )  subcategory = django_filters.ModelMultipleChoiceFilter(  widget=forms.CheckboxSelectMultiple(attrs={'onclick': 'this.form.submit()', 'class': 'checkbox'},))   condition = django_filters.MultipleChoiceFilter(choices=options,  widget=forms.CheckboxSelectMultiple(attrs={'onclick': 'this.form.submit()'}))   price = django_filters.NumericRangeFilter()   lowest = django_filters.OrderingFilter(choices=(  ('price', 'low to high'), ('-price', 'high to low')),  )   class Meta:  model = Product  fields = {  'category': ['in'],  'condition': ['icontains', ],  'price': ['contains'],  'city': ['icontains', ],  'subcategory': ['in', ],  'Manufacturer': ['icontains', ],  'model': ['icontains', ],   }   def my_custom_filter(self, queryset, name, value):  return Product.objects.filter(  Q(Product_name__icontains=value) |  Q(Short_des__icontains=value) |  Q(Description__icontains=value) |  Q(Manufacturer__icontains=value) |  Q(model__icontains=value)  )   def City_filter(self, queryset, name, value):  return Product.objects.filter(  Q(city__icontains=value)  )   def Manufacturer_filter(self, queryset, name, value):  return Product.objects.filter(  Q(Manufacturer__icontains=value)  )   def Model_filter(self, queryset, name, value):  return Product.objects.filter(  Q(model__icontains=value)  )   def Low_to_highFilter(self, queryset, name, value):  return Product.objects.order_by("-price")   def __init__(self, *args, **kwargs, ):  super(ProductFilter, self).__init__(*args, **kwargs)   category_input = args[0].get("category")  subcategory_input = args[0].get("subcategory")   if category_input:  category = Category.objects.all()[int(category_input)-1]  self.filters['subcategory'].extra.update({  'queryset': SubCategory.objects.filter(Category=category.id),  })   else:  self.filters['subcategory'].extra.update({  'queryset': SubCategory.objects.all()  })   if subcategory_input and not category_input:  category = Category.objects.get(subcat=subcategory_input)  self.filters['subcategory'].extra.update({  'queryset': SubCategory.objects.filter(Category=category.id)  })   self.filters['category'].extra.update({  'initial': "1"   })   

Я пробовал вместе с несколькими другими решениями ,но они, похоже, не работают

 self.filters['category'].extra.update({  'initial': "1"   })