简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM