Django:MultiChoiceField不显示创建后添加的保存的选项

2024-10-02 18:27:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试创建一个动态的产品模型,允许管理员创建自己的“选项集”并添加到产品中

例如,产品A有宽度为400mm、500mm和600mm的翻板阀

为了方便这一点,我创建了3个模型

型号.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)

…还有一张表格

表单.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毫米的翻板阀作为一个选项的产品optionstart的产品,事情就分崩离析了。任何新的选项都会显示在现有产品的管理区域中,甚至在保存产品时都会保留到数据库中,但它们不会在管理区域中显示为选中状态

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

为什么会发生这种情况?我能做些什么来修复它?谢谢


Tags: selftrue产品models选项nulllengthmax
1条回答
网友
1楼 · 发布于 2024-10-02 18:27:44

呃。。。大约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)

解决了我的问题

相关问题 更多 >