0
我目前正在尝试创建一个动态产品模型,该模型允许管理员为产品添加自己的“选项集”。Django:MultiChoiceField不会显示创建后添加的已保存选项
例如,产品A具有400mm,500mm和600mm宽度的瓣阀。
为了方便起见,我创建了3个模型。
models.py
# A container that can hold multiple ProductOptions
class ProductOptionSet(models.Model):
title = models.CharField(max_length=20)
# A string containing the for the various options available.
class ProductOption(models.Model):
value = models.CharField(max_length=255)
option_set = models.ForeignKey(ProductOptionSet)
# The actual product type
class HeadwallProduct(Product):
dimension_a = models.IntegerField(null=True, blank=True)
dimension_b = models.IntegerField(null=True, blank=True)
# (...more variables...)
flap_valve = models.CharField(blank=True, max_length=255, null=True)
...和...形式
forms.py
class HeadwallVariationForm(forms.ModelForm):
flap_valve = forms.MultipleChoiceField(required=False, widget=forms.SelectMultiple)
def __init__(self, *args, **kwargs):
super(HeadwallVariationForm, self).__init__(*args, **kwargs)
self.fields['flap_valve'].choices = [(t.id, t.value) for t in ProductOption.objects.filter(option_set=1)]
def save(self, commit=True):
instance = super(HeadwallVariationForm, self).save(commit=commit)
return instance
class Meta:
fields = '__all__'
model = HeadwallProduct
这最初创建的过程中工作正常一个产品。 MultipleChoiceForm中的列表填充了ProductOptionSet中的条目,并且可以保存该表单。
但是,当管理员添加700mm瓣阀作为ProductO的ProductOptionSet的选项时,事情就会崩溃。任何新的选项都将显示在现有产品的管理区域中 - 并且在产品保存时甚至会保留到数据库中 - 但它们不会在管理区域中显示为已选中。
如果创建产品B,则新选项按预期工作,但不能将新选项添加到现有产品。
为什么会发生这种情况,我该如何解决这个问题?谢谢。