2014-01-16 54 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别的东西。