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

后端 未结 26 1554
-上瘾入骨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:33

    if your need multiple read-only fields.you can use any of methods given below

    method 1

    class ItemForm(ModelForm):
        readonly = ('sku',)
    
        def __init__(self, *arg, **kwrg):
            super(ItemForm, self).__init__(*arg, **kwrg)
            for x in self.readonly:
                self.fields[x].widget.attrs['disabled'] = 'disabled'
    
        def clean(self):
            data = super(ItemForm, self).clean()
            for x in self.readonly:
                data[x] = getattr(self.instance, x)
            return data
    

    method 2

    inheritance method

    class AdvancedModelForm(ModelForm):
    
    
        def __init__(self, *arg, **kwrg):
            super(AdvancedModelForm, self).__init__(*arg, **kwrg)
            if hasattr(self, 'readonly'):
                for x in self.readonly:
                    self.fields[x].widget.attrs['disabled'] = 'disabled'
    
        def clean(self):
            data = super(AdvancedModelForm, self).clean()
            if hasattr(self, 'readonly'):
                for x in self.readonly:
                    data[x] = getattr(self.instance, x)
            return data
    
    
    class ItemForm(AdvancedModelForm):
        readonly = ('sku',)
    

提交回复
热议问题