[英]Select a valid choice.[<selection>]is not one of the available choices. Error
[英]ModelChoiceFilter gives “Select a valid choice. That choice is not one of the available choices.” when submitted
我正在使用 django-filters 根据品牌过滤我的产品。 当我提交表单时,我得到“选择一个有效的选择。该选择不是可用的选择之一。” 我使用ModelChoiceFilter因为文档说它适合 ForeignKey 关系。
表单成功呈现为 product.html 上预期的复选框:
提交表单并选中复选框时,会出现错误:
令人惊讶的是,当我将过滤器更改为ModelMultipleChoiceFilter时,我没有得到“选择一个有效的选择。该选择不是可用的选择之一。” 错误。 我想知道为什么ModelChoiceFilter会抛出这个错误。
这是我的代码:
模型.py
class Brand(models.Model):
bool_choices = (
(True, 'Yes'),
(False, 'No'),
)
name = models.CharField(max_length=30)
def __str__(self):
return f"{self.name}"
class Product(MPTTModel):
parent = TreeForeignKey('self', blank = True, null = True, related_name = 'children', on_delete=models.CASCADE)
name = models.CharField(max_length=50)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="brand") #one to many relationship between Brand and Product class
category = TreeManyToManyField(Category, blank = True)
过滤器.py
import django_filters
from product.models import Product, Category, Brand
from django.db import models
from django import forms
class BrandFilter(django_filters.FilterSet):
brand = django_filters.ModelChoiceFilter(queryset= Brand.objects.all(), widget=forms.CheckboxSelectMultiple, empty_label = None, to_field_name = 'name')
class Meta:
model = Product
fields = ('brand',)
视图.py
def product(request):
products = Product.objects.all()
brandFilter = BrandFilter(request.GET, queryset= products )
products = brandFilter.qs
context = {'products':products,'brandFilter': brandFilter}
return render(request, 'home/product.html', context)
产品.html
...
<div>
<form method = "get">
{{ brandFilter.form.as_p }}
<button class="btn btn-primary" type="submit"> Search </button>
</form>
</div>
<div>
{% for product in products %}
<div>
{{ product }}
</div>
{% endfor %}
</div>
我已尝试在激活 1 个复选框的情况下提交表单,但错误仍然存在:激活 1 个复选框时仍会出现错误
ModelChoiceFilter
只允许单个选择,因为它使用django.forms.models.ModelChoiceField来验证所选值。
但是,您使用forms.CheckboxSelectMultiple
小部件对其进行了实例化。 这意味着所选值作为列表传递,并且此行执行为
value = self.queryset.get(**{name: [<selected_value>,...]})
并引发self.queryset.model.DoesNotExist
异常。
如果您希望为一个产品选择多个品牌(即一个产品有多个品牌),则要使用的过滤器是ModelMultipleChoiceFilter
,它使用ModelMultipleChoiceField
并根据值列表进行验证。
否则,要保持产品和品牌之间的一对一关系并在您的表单中反映这一点,请使用选择单个值的表单小部件,例如RadioSelect 、 Select
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.