2014-01-16 70 views
0

我想改變formfield widget取決於其他域的值。默認選擇是因爲模型字段是外鍵。我的型號如下:Django管理內聯表單動態改變charfield的選擇域

class ProductFeatureValue(BaseName): 

    feature = models.ForeignKey('ProductTypeFeature') 

    class Meta: 
     verbose_name = _(u'Product Feature Value') 
     verbose_name_plural = _(u'Product Feature Values') 


class ProductFeature(models.Model): 

    product = models.ForeignKey('Product') 
    feature = models.ForeignKey('ProductTypeFeature') 
    value = models.ForeignKey('ProductFeatureValue') 

我的形式如下:

class ProductFeatureFormForInline(ModelForm): 

class Meta: 
    model = ProductFeature 

def __init__(self,*args,**kwargs): 
    super(ProductFeatureFormForInline,self).__init__(*args,**kwargs) 
    if isinstance(self.instance,ProductFeature): 
     try: 
      widget_type = self.instance.feature.product_type.producttypefeature_set.all()[0].widget #TODO Fix that 0 slice 
      if widget_type == u'TEXT': 
       self.fields['value'] = CharField(widget=TextInput()) 
      if widget_type == u'MULTIPLE_SELECT': 
       self.fields['value'].widget = MultipleChoiceField() 
     except: 
      pass 

它改變了場組件,但是,當它使它charfield與實例填充它,它顯示了該模型的ID不是價值(作者:1),並且以這種方式展示它是有道理的,但我想展示(作者:Dan Brown)。 我嘗試過初始值但不工作。任何提示,這將是高度讚賞。謝謝

回答

0

您的__unicode__()方法在模型上應該規定那裏顯示的內容,如果我沒有丟失什麼。

你的模型:

class ProductFeatureValue(BaseName): 

    [... snipped code ...] 

    def __unicode__(): 
     return self.feature 

這段代碼假定self.feature是要返回的東西,而不是在父BaseName別的東西。