Readonly for existing items only in Django admin inline

前端 未结 7 1272
长发绾君心
长发绾君心 2020-12-13 14:27

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

相关标签:
7条回答
  • 2020-12-13 15:21

    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.

    0 讨论(0)
提交回复
热议问题