我有一个模型,其中包含动态计算的 price
属性。我想在模型管理页面中显示此属性。所以我创建了自定义 ModelForm:
class ShipmentForm(forms.ModelForm):
price = forms.IntegerField()
class Meta:
model = models.Shipment
fields = [
'title',
'price',
]
但是我无法获得该形式的 price
值。
以下是我在管理面板中更改表单的方法:
class ShipmentAdmin(admin.ModelAdmin):
form = ShipmentForm
最佳答案
参见ModelAdmin.readonly_fields (Django 1.10 文档链接)。
A read-only field can not only display data from a model’s field, it can also display the output of a model’s method or a method of the ModelAdmin class itself.
这意味着您可以执行以下操作:
class ShipmentAdmin(admin.ModelAdmin):
readonly_fields = ('price', 'something_else')
def something_else(self, instance):
# calculate something else here
其中 price
是模型方法,something_else
是 ModelAdmin 方法。
关于python - 如何从模型属性填充 django 管理表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40340638/