Why are read-only form fields in Django a bad idea?

前端 未结 4 1631
天命终不由人
天命终不由人 2020-12-25 11:40

I\'ve been looking for a way to create a read-only form field and every article I\'ve found on the subject comes with a statement that \"this is a bad idea\". Now for an in

4条回答
  •  渐次进展
    2020-12-25 11:55

    When using a disabled field, you also need to make sure it remains populated correctly if the form fails validation. Here's my method, which also takes care of malicious attempts to change the data submitted:

    class MyForm(forms.Form):
    
        MY_VALUE = 'SOMETHING'
        myfield = forms.CharField(
            initial=MY_VALUE,
            widget=forms.TextInput(attrs={'disabled': 'disabled'})
    
        def __init__(self, *args, **kwargs):
    
            # If the form has been submitted, populate the disabled field
            if 'data' in kwargs:
                data = kwargs['data'].copy()
                self.prefix = kwargs.get('prefix')
                data[self.add_prefix('myfield')] = MY_VALUE
                kwargs['data'] = data
    
            super(MyForm, self).__init__(*args, **kwargs) 
    

提交回复
热议问题