python - 如何从模型属性填充 django 管理表单?

标签 python django django-admin

我有一个模型,其中包含动态计算的 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/

相关文章:

python - 如何阻止 opencv 调用 qDebug?

django - 使用 django runserver 开发服务器时如何提供静态文件?

django - 如何在django中的chatterbot View 中向终点发出POST请求?

python - 安装 django 1.9 后,Django 应用程序未显示在管理中

python - 将 Excel 中的字符串输入循环转换为 Python 列表

python - python 中的 NumPy ImportError - Dll 加载失败

python - 使用 lower() 进行不区分大小写的字典检查

django - 使用 unique=True 字段验证 ModelForm

django - 如何使用大规模数据限制 Django Admin.TabularInline 中的查询

python - django admin 从操作注册动态模型