我有两种型号:
class Box(models.Model):
...
material = models.ForeignKey('Material', related_name='box_materials',
on_delete=models.CASCADE)
class Material(models.Model):
...
name = models.CharField(max_length=20, unique=True)
def __str__(self):
return self.name
在form.py中,我得到了:
BoxesUpdateFormSet= inlineformset_factory(Entry, Box, form=BoxesForm, can_delete=True, extra=0)
class BoxesForm(ModelForm):
class Meta:
model = Box
fields = ['kg', 'material', 'price']
我想在模板中显示Box材质,但是{{box.material}}显示Select对象,而我只想显示文本。我已经尝试过{{box.material.value}},但只得到了ID。使用{{box.material.name}}我一无所获。
如何将“子模型”属性的值显示为文本?
答案 0 :(得分:2)
好吧,在forms.py
中字段下添加以下代码:
from django.forms import TextInput
widgets = {
'material': TextInput(attrs={'readonly': 'readonly'})
}
此代码的作用是,将您的 material 表对象设为只读。
编辑-包含textinput
导入
完成forms.py
from django.forms import TextInput
class BoxesForm(ModelForm):
class Meta:
model = Box
fields = ['kg', 'material', 'price']
widgets = {
'material': TextInput(attrs={'readonly': 'readonly'})
}