简体   繁体   中英

How to get django admin change form to pre-select choice field?

I have a model field with choices, as defined here:

class Pack(models.Model):
    SIZE_10x20 = Decimal(200.000)
    SIZE_10x10 = Decimal(100.000)
    SIZE_5x10 = Decimal(50.000)

    size_code_choices = (
        (SIZE_5x10, '5x10'),
        (SIZE_10x10, '10x10'),
        (SIZE_10x20, '10x20'),
    )
    size_code = models.DecimalField(max_digits=7,
                                    decimal_places=3,
                                    choices=size_code_choices,
                                    default=SIZE_10x20)

My admin.py uses the default forms:

class PackAdmin(admin.ModelAdmin):
    list_display = ('size_code')
    fields = ('size_code')

admin.site.register(Pack, PackAdmin)

However, when I open up my admin panel and check the model instance change form the dropdown menu is not pre-set to the choice that is stored in the database. I've attached two images to demonstrate what I mean:

List display for all model instances

Change Model Form

It simply selects the one at the top of the list. I would like users to be able to make small changes to the model without always having to check and reset this field everytime this form is used.

I've looked into overriding ModelAdmin.get_changeform_initial_data(request) but to no avail.

I have a similar choice selection on a Model CharField and do not have this issue with it. Is there something going on with the DecimalField that I am unaware of?

You need to create a form for your model, settings initial values:

seehttps://docs.djangoproject.com/en/2.1/ref/forms/fields/#initial

Then replace the form on your admin:

see https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form

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