dimazubrik dimazubrik - 1 year ago 122
Python Question

How to populate django admin form from model property?

I have model which among other fields contains

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 = [

However I can't get
value in that form.

Here's how I change form in admin panel:

class ShipmentAdmin(admin.ModelAdmin):
form = ShipmentForm

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download