Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *