dimazubrik dimazubrik - 1 month ago 21
Python Question

How to populate django admin form from model property?

I have model which among other fields contains

price
property which is calculated dynamically. I want to display this property in model admin page. So I've created custom ModelForm:

class ShipmentForm(forms.ModelForm):
price = forms.IntegerField()

class Meta:
model = models.Shipment
fields = [
'title',
'price',
]


However I can't get
price
value in that form.

Here's how I change form in admin panel:

class ShipmentAdmin(admin.ModelAdmin):
form = ShipmentForm

Answer

See ModelAdmin.readonly_fields (Django 1.10 docs link).

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.

This means that you can do:

class ShipmentAdmin(admin.ModelAdmin):
    readonly_fields = ('price', 'something_else')

    def something_else(self, instance):
        # calculate something else here

Where price is a model method, and something_else is a ModelAdmin method.