【发布时间】: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