Disable choice list in Django admin, only for editing

吃可爱长大的小学妹 提交于 2019-12-02 09:51:38

Setting the attribute to disabled or readonly only affects the way the widgets are displayed. It doesn't actually stop somebody submitting a post request that changes those fields.

It might be a better approach to override get_readonly_fields for your model.

class OrderModelAdmin(admin.Model
    def get_readonly_fields(self, request, obj=None):
        if self.obj.pk:
            return ['description', 'city_code', 'customer']
        else:
            return []

The answer of @Alasdair is better than this one (because this one doesn't prevent a submission). But I post it, just in case someone wants the equivalent to 'readonly' for ModelChoiceField.

self.fields['customer_id'].widget.widget.attrs['disabled'] = 'disabled'

Notice, that for a ChoiceField is enought something like this:

self.fields['city_code'].widget.attrs['disabled'] = True
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!