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

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

    I made a MixIn class which you may inherit to be able to add a read_only iterable field which will disable and secure fields on the non-first edit:

    (Based on Daniel's and Muhuk's answers)

    from django import forms
    from django.db.models.manager import Manager
    
    # I used this instead of lambda expression after scope problems
    def _get_cleaner(form, field):
        def clean_field():
             value = getattr(form.instance, field, None)
             if issubclass(type(value), Manager):
                 value = value.all()
             return value
        return clean_field
    
    class ROFormMixin(forms.BaseForm):
        def __init__(self, *args, **kwargs):
            super(ROFormMixin, self).__init__(*args, **kwargs)
            if hasattr(self, "read_only"):
                if self.instance and self.instance.pk:
                    for field in self.read_only:
                        self.fields[field].widget.attrs['readonly'] = "readonly"
                        setattr(self, "clean_" + field, _get_cleaner(self, field))
    
    # Basic usage
    class TestForm(AModelForm, ROFormMixin):
        read_only = ('sku', 'an_other_field')
    

提交回复
热议问题