In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

后端 未结 26 972
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:09

In a Django form, how do I make a field read-only (or disabled)?

When the form is being used to create a new entry, all fields should be enabled - but when the recor

26条回答
  •  孤街浪徒
    2020-11-22 04:12

    As a useful addition to Humphrey's post, I had some issues with django-reversion, because it still registered disabled fields as 'changed'. The following code fixes the problem.

    class ItemForm(ModelForm):
    
        def __init__(self, *args, **kwargs):
            super(ItemForm, self).__init__(*args, **kwargs)
            instance = getattr(self, 'instance', None)
            if instance and instance.id:
                self.fields['sku'].required = False
                self.fields['sku'].widget.attrs['disabled'] = 'disabled'
    
        def clean_sku(self):
            # As shown in the above answer.
            instance = getattr(self, 'instance', None)
            if instance:
                try:
                    self.changed_data.remove('sku')
                except ValueError, e:
                    pass
                return instance.sku
            else:
                return self.cleaned_data.get('sku', None)
    

提交回复
热议问题