jhrs21
jhrs21

Reputation: 391

Disable choice list in Django admin, only for editing

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.

Upvotes: 0

Views: 2182

Answers (2)

jhrs21
jhrs21

Reputation: 391

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

Upvotes: 1

Alasdair
Alasdair

Reputation: 308829

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

Upvotes: 3

Related Questions