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)
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
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()
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()