【问题标题】:Django admin inline form change choice field to charfield dynamicallyDjango admin 内联表单将选择字段动态更改为 charfield
【发布时间】:2014-02-05 01:27:14
【问题描述】:

我想根据其他字段值更改表单字段小部件。默认是选择,因为模型字段是外键。我的模型如下:

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),这样显示它是有意义的,但我想显示(作者:丹布朗)。 我尝试过使用初始值但没有工作。任何这样做的提示将不胜感激。谢谢

【问题讨论】:

    标签: python django django-forms django-admin


    【解决方案1】:

    如果我没有遗漏什么,您在模型上的 __unicode__() 方法应该指示那里显示的内容。

    在您的模型上:

    class ProductFeatureValue(BaseName):
    
        [... snipped code ...]
    
        def __unicode__():
            return self.feature
    

    这个 sn-p 假设 self.feature 是您想要返回的,而不是父级 BaseName 上的其他内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 2012-10-19
      • 2021-01-07
      相关资源
      最近更新 更多