问题
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