Search code examples
django-admin

In the Django-admin, interleave readonly and (regular) editable fields


In my Django admin, there are a few fields that I would like to define as read only. If I use readonly_fields, these float to the bottom of the page. This is not desirable in my use case, I want to preserve the ordering I had before I set them as read only. How should I do this?


Solution

  • ModelAdmin.readonly_fields not affect on fields_order and not add any additional field in AdminForm if fields or fieldsets are defined.

    in normal mode:

    class MyModelAdmin(ModelAdmin):    
        fields = 'title', 'description', 'my_first_readonly', 'visible'
        readonly_fields = 'my_first_readonly', 'my_second_readonly' 
    

    The order of fields should be 'title', 'description', 'my_first_readonly', 'visible'. 'my_second_readonly' not appears, because it not listed in fields.

    more info here:

    fields

    how it works with readonly: https://docs.djangoproject.com/en/5.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields

    readonly fields.

    you can find mention about field ordering there: https://docs.djangoproject.com/en/5.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

    Only one reason, why order of fields can change itself: ModelAdmin.get_fields or/and ModelAdmin.get_fieldsets are overridden

    more here: https://docs.djangoproject.com/en/5.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_fields