Django set field value after a form is initialized

后端 未结 9 1905
陌清茗
陌清茗 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
    
    0 讨论(0)
  • 2020-12-12 15:26

    Another way to do this, if you have already initialised a form (with or without data), and you need to add further data before displaying it:

    form = Form(request.POST.form)
    form.data['Email'] = GetEmailString()
    
    0 讨论(0)
  • 2020-12-12 15:29

    Something like Nigel Cohen's would work if you were adding data to a copy of the collected set of form data:

    form = FormType(request.POST)
    if request.method == "POST":
        formcopy = form(request.POST.copy())
        formcopy.data['Email'] = GetEmailString()
    
    0 讨论(0)
提交回复
热议问题