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) wh
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.