Django set field value after a form is initialized

后端 未结 9 1923
陌清茗
陌清茗 2020-12-12 14:50

I am trying to set the field to a certain value after the form is initialized.

For example, I have the following class.

class CustomForm(forms.Form)         


        
9条回答
  •  [愿得一人]
    2020-12-12 15:24

    Just change your Form.data field:

    class ChooseProjectForm(forms.Form):
        project = forms.ModelChoiceField(queryset=project_qs)
        my_projects = forms.BooleanField()
    
        def __init__(self, *args, **kwargs):
            super(ChooseProjectForm, self).__init__(*args, **kwargs)
            self.data = self.data.copy()  # IMPORTANT, self.data is immutable
            # any condition:
            if self.data.get('my_projects'):
                my_projects = self.fields['project'].queryset.filter(my=True)
                self.fields['project'].queryset = my_projects
                self.fields['project'].initial = my_projects.first().pk
                self.fields['project'].empty_label = None  # disable "-----"
                self.data.update(project=my_projects.first().pk)  # Update Form data
                self.fields['project'].widget = forms.HiddenInput()  # Hide if you want
    

提交回复
热议问题