0

readonly_fields function works properly when I use it with individual models, but it doesn't work with models which are tabularly inlined.

Could somebody help in understanding how to mark fields read only when we deal with models inlined to each other on admin page ?

Thanks.

ans2human
  • 2,300
  • 1
  • 14
  • 29

1 Answers1

0

If you just want to set a readonly field on the inline, you can do:

class SomethingInline(admin.TabularInline):
    model = Something
    extra = 0
    readonly_fields = ('field1',)

If you want to make the entire inline formset readonly on the parent form, you can try this:

class SomethingInline(admin.TabularInline):
    model = Something
    extra = 0
    # Set all your fields here:
    readonly_fields = ('field1', 'field2', 'field3')

    # Or instead return all your fields here if this should be conditional:
    def get_readonly_fields(self, request, obj=None):
        return ('field1', 'field2', 'field3')

    def has_add_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

In the last example it will still render all the values for existing inline items, but you cannot add/edit/remove from the interface. this would in effect make the entire formset readonly.

Note: I did not override has_change_permission() to return False, because that would prevent the existing items from being shown.


If you don't want to specify all your fields manually, implement get_readonly_fields() from one of the solutions here: Django admin - make all fields readonly

malberts
  • 2,488
  • 1
  • 11
  • 16