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

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

    Two more (similar) approaches with one generalized example:

    1) first approach - removing field in save() method, e.g. (not tested ;) ):

    def save(self, *args, **kwargs):
        for fname in self.readonly_fields:
            if fname in self.cleaned_data:
                del self.cleaned_data[fname]
        return super(, self).save(*args,**kwargs)
    

    2) second approach - reset field to initial value in clean method:

    def clean_(self):
        return self.initial[] # or getattr(self.instance, fieldname)
    

    Based on second approach I generalized it like this:

    from functools                 import partial
    
    class (...):
    
        def __init__(self, ...):
            ...
            super(, self).__init__(*args, **kwargs)
            ...
            for i, (fname, field) in enumerate(self.fields.iteritems()):
                if fname in self.readonly_fields:
                    field.widget.attrs['readonly'] = "readonly"
                    field.required = False
                    # set clean method to reset value back
                    clean_method_name = "clean_%s" % fname
                    assert clean_method_name not in dir(self)
                    setattr(self, clean_method_name, partial(self._clean_for_readonly_field, fname=fname))
    
        def _clean_for_readonly_field(self, fname):
            """ will reset value to initial - nothing will be changed 
                needs to be added dynamically - partial, see init_fields
            """
            return self.initial[fname] # or getattr(self.instance, fieldname)
    

提交回复
热议问题