Disable choice list in Django admin, only for editing

Deadly 提交于 2019-12-20 05:46:08

问题


I want to disable some fields when I am editing an object. I have managed to do this for text fields, but it's been impossible for a dropdown list (choice list).

I am doing this action in the constructor of the form.

class OrderModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            self.fields['description'].widget.attrs['readonly'] = True
            self.fields['city_code'].widget.attrs['disabled'] = True

Notice how I made it for both with different keywords, but I can't do it for my customer_id field.


回答1:


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 []



回答2:


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


来源:https://stackoverflow.com/questions/33636624/disable-choice-list-in-django-admin-only-for-editing

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