简体   繁体   中英

Django: MultiChoiceField does not show saved choices added after creation

I am currently trying to create a dynamic product model that will allow admins to create add their own "option sets" to products.

For example, Product A has flap valve with 400mm, 500mm and 600mm widths available.

To facilitate this I have created 3 models.

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)

...and a form...

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

This works fine for during the initial creation of a product. The list from the MultipleChoiceForm is populated with entries from the ProductOptionSet and the form can be saved.

However, when the admin adds a 700mm flap valve as an option to the ProductOptionSet of Product A things fall apart. Any new options will show up in the admin area of the existing product - and will even be persisted to the database when the product is saved - but they will not be shown as selected in the admin area.

If a Product B is created the new options work as intended, but you cannot add new options to an existing product.

Why does this happen and what can I do to fix it? Thanks.

Urgh... after about 4 hours I figured it out...

Changing:

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

to

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

Fixed my issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM