简体   繁体   中英

readonly_fields function doesn't work in Django Admin with models tabularly inlined

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.

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

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