Menu Close

How to make a field readonly (or disabled) so that it cannot be edited in a Python Django form?

To make a field readonly (or disabled) so that it cannot be edited in a Python Django form, we can set the readonly attribute of a field to True.

For instance, we write

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

    def clean_sku(self):
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            return instance.sku
        else:
            return self.cleaned_data['sku']

to create the ItemForm with the

self.fields['sku'].widget.attrs['readonly'] 

dictionary value set to True to make the sku field readonly.

Posted in Python, Python Answers