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

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

    I was going into the same problem so I created a Mixin that seems to work for my use cases.

    class ReadOnlyFieldsMixin(object):
        readonly_fields =()
    
        def __init__(self, *args, **kwargs):
            super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)
            for field in (field for name, field in self.fields.iteritems() if name in self.readonly_fields):
                field.widget.attrs['disabled'] = 'true'
                field.required = False
    
        def clean(self):
            cleaned_data = super(ReadOnlyFieldsMixin,self).clean()
            for field in self.readonly_fields:
               cleaned_data[field] = getattr(self.instance, field)
    
            return cleaned_data
    

    Usage, just define which ones must be read only:

    class MyFormWithReadOnlyFields(ReadOnlyFieldsMixin, MyForm):
        readonly_fields = ('field1', 'field2', 'fieldx')
    

提交回复
热议问题