37

I have a tabular inline model in the Django admin. I need 1 of the fields to not be changeable after it has been created, but setting it as readonly (via readonly_fields) which works fine, but turns the field into a label when clicking 'Add another item' instead of a dropdown.

Is there a way to keep a field readonly, but still allow new items to be created with the proper field input?

Thanks!

Thomas

Edit: Managed to figure it out by way of a custom widget

class ReadOnlySelectWidget(forms.Select):
    def render(self, name, value, attrs=None):
        if value:
            final_attrs = self.build_attrs(attrs, name=name)
            output = u'<input value="%s" type="hidden" %s />' % (value, flatatt(final_attrs))
            return mark_safe(output + str(self.choices.queryset.get(id=value)))
        else:
            return super(ReadOnlySelectWidget, self).render(name, value, attrs)

It just turns it into a hidden if there is a value, won't work in every situation (only really works with 1 read only field).

1
  • 1
    add your solution as answer so that the question shows up as answered :)
    – ashwoods
    May 11, 2011 at 21:26

6 Answers 6

79

Having the same problem, I came across this fix:

Create two inline objects, one with no change permission, and the other with all the fields read-only. Include both in the model admin.

class SubscriptionInline(admin.TabularInline):
    model = Subscription
    extra = 0
    readonly_fields = ['subscription', 'usedPtsStr', 'isActive', 'activationDate', 'purchaseDate']

    def has_add_permission(self, request):
        return False

class AddSupscriptionInline(admin.TabularInline):
    model = Subscription
    extra = 0
    fields = ['subscription', 'usedPoints', 'isActive', 'activationDate', 'purchaseDate']

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

    # For Django Version > 2.1 there is a "view permission" that needs to be disabled too (https://docs.djangoproject.com/en/2.2/releases/2.1/#what-s-new-in-django-2-1)
    def has_view_permission(self, request, obj=None):
        return False

Include them in the same model admin:

class UserAdmin(admin.ModelAdmin):
    inlines = [ AddSupscriptionInline, SubscriptionInline]

To add a new subscription I use the AddSubscriptionInline in the admin. Once it is saved, the new subscription disappears from that inline, but now does appear in the SubscriptionInline, as read only.

For SubscriptionInline, it is important to mention extra = 0, so it won't show junk read-only subscriptions. It is better also to hide the add option for SubscriptionInline, to allow adding only via AddSubscriptionInline, by setting the has_add_permission to always return False.

Not perfect at all, but it's the best option for me, since I must provide the ability to add subscriptions on the user admin page, but after one is added, it should be changed only via the internal app logic.

5
  • 3
    I did similar to this but modified the queryset of the Inline for new records (AddSubscriptionInline in the example): def queryset(self, request): return super(AddSubscriptionInline, self).queryset(request).none() and added max_num = 0 to the Inline for existing records (SubscriptionInline in the example).
    – jenniwren
    Jul 24, 2015 at 1:38
  • I used this solution as well. It works like magic. One of the most elegant hacks I've ever seen! Apr 14, 2017 at 14:07
  • 1
    Awsom hack I have ever seen in django admin. Thanks a lot !! Sep 3, 2017 at 10:49
  • 1
    The key for me was using extra = 1 and max_num = 1 in AddSubscriptionInline as that doesn't include the "Add another..." link below the form. May 14, 2020 at 19:46
  • This is beautiful Oct 13, 2022 at 11:57
15

You can achieve this with only a single inline like so:

class MyInline(admin.TabularInline):
    fields = [...]
    extra = 0

    def has_change_permission(self, request, obj):
        return False
5
  • Thank you so much. This is the least involving answer here, and it works perfectly. Nov 3, 2020 at 22:54
  • 2
    Awesome answer, this is what I was looking for. As of Django 3.x, args should be (self, request, obj) (assuming a related model) and only has_change_permission is needed. Nov 11, 2020 at 19:06
  • 1
    thanks @MattSanders -- updated the answer to account for Django 3.x Nov 14, 2020 at 19:46
  • Kinda hacky, but this works! Thanks @Travis Lloyd Jun 9, 2021 at 0:01
  • 2
    This answer is nice, but only if you want all fields to be readonly for existing items. Technically the original questions was about a specific field, so it might be good to clarify this limitation in the answer? Jun 9, 2022 at 18:56
3

I actually came across another solution that seems to work really well (I can't take credit for this, but link here).

You can define the get_readonly_fields method on your TabularInline and set the read only fields appropriately when there is an object (editing) vs when there is not one (creating).

def get_readonly_fields(self, request, obj=None):
    if obj is not None:  # You may have to check some other attrs as well
        # Editing an object
        return ('field_name', )
    else:
        # Creating a new object
        return ()

This has the effect of making your target field readonly when you're editing an exiting instance while allowing it to be editable when creating a new instance.


As pointed out below in the comment, this doesn't quite work as intended because the obj passed is is actually the parent... There's an old django ticket that discusses this here.

2
  • 6
    Unfortunately, this doesn't work as described here; the obj passed in is not an instance of the "inlined" model, it's an instance of the parent/related model. I'd sort of consider this a Django bug, honestly. Mar 7, 2019 at 0:00
  • Yea I realized that after I tried to implement this is a different case. In one case I was able to solve the problem but in the other I was not. I've updated the post and added a link to the django ticket that discusses this issue.
    – RoHS4U
    Mar 7, 2019 at 23:55
2

According to this post this issue has been reported as a bug in Ticket15602.

A workaround would be to override the clean method of the inline model in forms.py and raise an error when an existing inline is changed:

class NoteForm(forms.ModelForm):
    def clean(self):
        if self.has_changed() and self.initial:
            raise ValidationError(
                'You cannot change this inline',
                code='Forbidden'
            )
        return super().clean()

    class Meta(object):
        model = Note
        fields='__all__'

The above gives a solution on the model level.

To raise an error when a specific field is changed, the clean_<field> method can help. For example, if the field is a ForeignKey called category:

class MyModelForm(forms.Form):
    pass  # Several lines of code here for the needs of the Model Form

# The following form will be called from the admin inline class only
class MyModelInlineForm(MyModelForm):
    def clean_category(self):
        category = self.cleaned_data.get('category', None)
        initial_value = getattr(
            self.fields.get('category', None), 
            'initial', 
            None
        )
        if all(
            (
                self.has_changed(),
                category.id != initial_value,
            )
        ):
            raise forms.ValidationError(
                _('You cannot change this'),
                code='Forbidden'
            )
        return category


    class Meta:
        # Copy here the Meta class of the parent model 
2

This code work perfectly according to your requirements.

Actually i got this answer from my own question but specific to my problem and i removed some lines related to my problem. And credit goes to @YellowShark. Check here my question.

Once you created new inline then you will be not able to edit existing inline.

class XYZ_Inline(admin.TabularInline):
    model = YourModel

class RequestAdmin(admin.ModelAdmin):
inlines = [XYZ_Inline, ]

# If you wanted to manipulate the inline forms, to make one of the fields read-only:
def get_inline_formsets(self, request, formsets, inline_instances, obj=None):
    inline_admin_formsets = []
    for inline, formset in zip(inline_instances, formsets):
        fieldsets = list(inline.get_fieldsets(request, obj))
        readonly = list(inline.get_readonly_fields(request, obj))
        prepopulated = dict(inline.get_prepopulated_fields(request, obj))
        inline_admin_formset = helpers.InlineAdminFormSet(
            inline, formset, fieldsets, prepopulated, readonly,
            model_admin=self,
        )

        if isinstance(inline, XYZ_Inline):
            for form in inline_admin_formset.forms:
            #Here we change the fields read only.
                    form.fields['some_fields'].widget.attrs['readonly'] = True

        inline_admin_formsets.append(inline_admin_formset)
    return inline_admin_formsets

You can add only new inline and read only all existing inline.

1

This is possible with a monkey patch.

The following example will make the "note" field to be read only for existing AdminNote objects. Unlike converting fields to be hidden like suggested in other answers, this will actually remove fields from the submit/validation workflow (which is more secure and uses existing field renderers).

#
# app/models.py
#

class Order(models.Model):
    pass

class AdminNote(models.Model):
    order = models.ForeignKey(Order)
    time = models.DateTimeField(auto_now_add=True)
    note = models.TextField()


#
# app/admin.py
#

import monkey_patches.admin_fieldset

...

class AdminNoteForm(forms.ModelForm):
    class Meta:
        model = AdminNote

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.get_readonly_fields():
            del self.fields[field]

    def get_readonly_fields(self):
        if self.instance.pk:
            return ['note']
        return []


class AdminNoteInline(admin.TabularInline):
    model = AdminNote
    form = AdminNoteForm
    extra = 1
    fields = 'note', 'time'
    readonly_fields = 'time',


@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    inlines = AdminNoteInline,


#
# monkey_patches/admin_fieldset.py
#

import django.contrib.admin.helpers


class Fieldline(django.contrib.admin.helpers.Fieldline):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if hasattr(self.form, 'get_readonly_fields'):
            self.readonly_fields = list(self.readonly_fields) + list(self.form.get_readonly_fields())

django.contrib.admin.helpers.Fieldline = Fieldline
1
  • In the case where I tried this it gave me a ValueError during form validation: Cannot assign None: "MyModel.field" does not allow null values.
    – towr
    Jan 15, 2015 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.