[Django]-How to make some Django Inlines Read Only

2👍

You have to override your inline form and check the value on the instance in the __init__().

Example:

class AuthorBookInlineForm(forms.ModelForm):
    model = Book

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.created_ts.year <= 2001:
            for f in self.fields:
                  self.fields[f].widget.attrs['readonly'] = 'readonly'

Don’t forget to set the form value on your inline…

class AuthorBookInline(admin.TabularInline):
    model = Book
    form = AuthorBookInlineForm
    extra = 0
👤Jeremy

0👍

In Django >= 2.1 (afaik)

You have to override your inline form and check the value on the instance in the init().

Disabling a field by setting self.fields['field'].disabled = true

Example:

class AuthorBookInlineForm(forms.ModelForm):
    model = Book

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.created_ts.year <= 2001:
            for f in self.fields:
                  self.fields[f].disabled = true

Don’t forget to set the form value on your inline:

class AuthorBookInline(admin.TabularInline):
    model = Book
    form = AuthorBookInlineForm
    extra = 0

Leave a comment