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

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

    If you are working with Django ver < 1.9 (the 1.9 has added Field.disabled attribute) you could try to add following decorator to your form __init__ method:

    def bound_data_readonly(_, initial):
        return initial
    
    
    def to_python_readonly(field):
        native_to_python = field.to_python
    
        def to_python_filed(_):
            return native_to_python(field.initial)
    
        return to_python_filed
    
    
    def disable_read_only_fields(init_method):
    
        def init_wrapper(*args, **kwargs):
            self = args[0]
            init_method(*args, **kwargs)
            for field in self.fields.values():
                if field.widget.attrs.get('readonly', None):
                    field.widget.attrs['disabled'] = True
                    setattr(field, 'bound_data', bound_data_readonly)
                    setattr(field, 'to_python', to_python_readonly(field))
    
        return init_wrapper
    
    
    class YourForm(forms.ModelForm):
    
        @disable_read_only_fields
        def __init__(self, *args, **kwargs):
            ...
    

    The main idea is that if field is readonly you don't need any other value except initial.

    P.S: Don't forget to set yuor_form_field.widget.attrs['readonly'] = True

提交回复
热议问题