简体   繁体   中英

Django admin inline form change choice field to charfield dynamically

I want to change formfield widget depend on other field value. Default is select because model field is foreign key. 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). 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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