[英]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.