如何在 forms.BooleanField 中传递请求以从 Django 中的数据库中获取数据?

How to pass request in forms.BooleanField to get the data from database in Django?

我正在使用 forms.BooleanField 进行复选框过滤。我一直无法从数据库中获取数据。

含义: 如果用户点击 SAMSUNG 产品,数据应过滤所有 SAMSUNG 产品。

好吧,我已经尝试从数据库中获取品牌列表并且效果很好,但是当我点击特定品牌时它不会过滤特定品牌。 (它只是刷新并显示相同的数据

Code goes here:

forms.py

class BrandForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        brands = Product.objects.filter(category=1).values_list('brand', flat=True)
        for brand in brands:
            self.fields[f'{brand}'] = forms.BooleanField(label=f'{brand}', required=False)

views.py

def product(request):
    product = Product.objects.all().order_by('-id')
    formBrand = BrandForm()
          
    return render(request, 'list/product.html', 
    {'product': product, 'formBrand':formBrand}
    )

index.html

<form action="{% url 'main:product' %}" method="get">
            {{ formBrand.as_p }}
            <input type="submit" value="OK">
          </form>

所有代码应该实现什么?

编辑 1

models.py

class Product(models.Model):
    name = models.CharField(max_length=1330)
    title = models.CharField(max_length=1330)
    image_src = models.URLField(max_length=1330,null=True, blank=True)
    link_href = models.URLField(max_length=1330,null=True, blank=True)
    brand = models.CharField(max_length = 1330, null=True, blank=True)
    price = models.DecimalField(max_digits=15, decimal_places=2)
    category = models.IntegerField(default=1, choices=PRODUCT_CHOICES)
    created = models.DateTimeField(auto_now_add=True)

我认为你处理表单的方式不对,首先你需要有 POST 方法从表单中获取数据,然后根据表单中的选择过滤产品并重新呈现页面。

所以表格应该是:

<form action="{% url 'main:productdata' %}" method="POST">
            {{ formBrand.as_p }}
            <input type="submit" value="OK">
          </form>

在您看来:

def product(request):
    product = Product.objects.all().order_by('-id')
    if request.method == 'GET':
        formBrand = BrandForm()
    elif request.method == 'POST':
        formBrand = BrandForm(request.POST)
        if formBrand.is_valid():
           brand_names = []
           # get list of brand name as form name
           for brand_name in formBrand.cleaned_data:
              if formBrand.cleaned_data[brand_name] == True:
                 brand_names.append(brand_name)
           if brand_names:
              product = Product.objects.filter(brand__in=brand_names).order_by('-id')
          
    return render(request, 'list/product.html', 
    {'product': product, 'formBrand':formBrand}
    )