In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

后端 未结 26 1005
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:09

In a Django form, how do I make a field read-only (or disabled)?

When the form is being used to create a new entry, all fields should be enabled - but when the recor

26条回答
  •  -上瘾入骨i
    2020-11-22 04:26

    I ran across a similar problem. It looks like I was able to solve it by defining a "get_readonly_fields" method in my ModelAdmin class.

    Something like this:

    # In the admin.py file
    
    class ItemAdmin(admin.ModelAdmin):
    
        def get_readonly_display(self, request, obj=None):
            if obj:
                return ['sku']
            else:
                return []
    

    The nice thing is that obj will be None when you are adding a new Item, or it will be the object being edited when you are changing an existing Item.

    get_readonly_display is documented here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-methods

提交回复
热议问题