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 中的条目,并且可以保存表单。

但是,当管理员将 700 毫米瓣阀作为选项添加到产品 A 的产品选项集时,事情就会分崩离析。任何新选项都将显示在现有产品的管理区域中 - 甚至在保存产品时将保留到数据库中 - 但它们不会在管理区域中显示为选中状态。

如果创建了产品 B,则新选项按预期工作,但无法向现有产品添加新选项。

为什么会发生这种情况,我该怎么做才能解决它?谢谢。

呃...大约 4 小时后我想通了...

改变:

class ProductOption(models.Model):
value = models.CharField(max_length=20)
option_set = models.ForeignKey(ProductOptionSet)

class ProductOption(models.Model):
option_value = models.CharField(max_length=20)
option_set = models.ForeignKey(ProductOptionSet)

修复了我的问题。

最新更新