簡體   English   中英

Django管理員內聯表單將選擇字段動態更改為charfield

[英]Django admin inline form change choice field to charfield dynamically

我想根據其他字段值更改formfield小部件。 由於模型字段是外鍵,因此默認為select。 我的模型如下:

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),這樣顯示是有意義的,但是我想顯示(作者:丹棕色)。 我嘗試使用初始值,但不起作用。 這樣做的任何提示將不勝感激。 謝謝

如果我不缺少任何內容,則模型上的__unicode__()方法應指示那里顯示的內容。

在您的模型上:

class ProductFeatureValue(BaseName):

    [... snipped code ...]

    def __unicode__():
        return self.feature

此代碼段假定self.feature是您要返回的內容,而不是父BaseName上的其他BaseName

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM