disabled field is not passed through - workaround needed

后端 未结 7 512
夕颜
夕颜 2020-12-10 03:29

I have a form with which I want to update a MyModel object. On the model there is a unique_together constraint, fieldA together with fieldB. In the form in the clean method

7条回答
  •  温柔的废话
    2020-12-10 04:03

    You can put it in the form class like this:

    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) 
    

    The way it works, is it tests to see if any data has been passed in to the form constructor. If it has, it copies it (the uncopied data is immutable) and then puts the initial value in before continuing to instantiate the form.

提交回复
热议问题