简体   繁体   English

Django管理员内联表单将选择字段动态更改为charfield

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

I want to change formfield widget depend on other field value. 我想根据其他字段值更改formfield小部件。 Default is select because model field is foreign key. 由于模型字段是外键,因此默认为select。 My models are as follows: 我的模型如下:

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')

And my form is as follows: 我的形式如下:

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

It changes the fields widget but when it make it charfield and populate it with instance it shows the id of the model not the value (author : 1) and it makes sense to show it that way, but i want to show(author: Dan Brown). 它更改了字段小部件,但是当它使它成为charfield并用实例填充它时,它显示的是模型的ID而不是值(作者:1),这样显示是有意义的,但是我想显示(作者:丹棕色)。 I have tried with initial values but not working. 我尝试使用初始值,但不起作用。 Any tips of doing that will be highly appreciated. 这样做的任何提示将不胜感激。 Thanks 谢谢

Your __unicode__() method on the model should dictate what is shown there, if I'm not missing something. 如果我不缺少任何内容,则模型上的__unicode__()方法应指示那里显示的内容。

On your model: 在您的模型上:

class ProductFeatureValue(BaseName):

    [... snipped code ...]

    def __unicode__():
        return self.feature

This snippet assumes that self.feature is what you want to return, and not something else on the parent BaseName . 此代码段假定self.feature是您要返回的内容,而不是父BaseName上的其他BaseName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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