2017-03-17 27 views
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,則新選項按預期工作,但不能將新選項添加​​到現有產品。

爲什麼會發生這種情況,我該如何解決這個問題?謝謝。

回答

0

Urgh ......大約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) 

固定我的問題。

相關問題