Since you're not passing in POST data, I'll assume that what you are trying to do is set an initial value that will be displayed in the form. The way you do this is with the initial
keyword.
form = CustomForm(initial={'Email': GetEmailString()})
See the Django Form docs for more explanation.
If you are trying to change a value after the form was submitted, you can use something like:
if form.is_valid():
form.cleaned_data['Email'] = GetEmailString()
Check the referenced docs above for more on using cleaned_data
If you've already initialized the form, you can use the initial property of the field. For example,
form = CustomForm()
form.fields["Email"].initial = GetEmailString()
If you want to do it within the form's __init__
method for some reason, you can manipulate the initial
dict:
class MyForm(forms.Form):
my_field = forms.CharField(max_length=255)
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.initial['my_field'] = 'Initial value'
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()
If you have initialized the form like this
form = CustomForm()
then the correct way as of Jan 2019, is to use .initial
to replace the data. This will replace the data in the intial
dict that goes along with the form. It also works if you have initialized using some instance such as form = CustomForm(instance=instance)
To replace data in the form, you need to
form.initial['Email'] = GetEmailString()
Generalizing this it would be,
form.initial['field_name'] = new_value
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With