Django field value value after form initialization

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

For example, I have the following class.

class CustomForm(forms.Form): Email = forms.EmailField(min_length=1, max_length=200) 

In the view, I want to be able to do something like this:

 form = CustomForm() form["Email"] = GetEmailString() return HttpResponse(t.render(c)) 
+96
django
May 01 '09 at 21:39
source share
8 answers

Since you are not transmitting POST data, I assume that what you are trying to do is set the initial value that will be displayed on the form. How you do this is the initial keyword.

 form = CustomForm(initial={'Email': GetEmailString()}) 

See the Django Form docs for more details.

If you are trying to change the value after submitting the form, you can use something like:

 if form.is_valid(): form.cleaned_data['Email'] = GetEmailString() 

Check out the docs above to learn more about using cleaned_data

+117
May 01 '09 at 21:58
source share

If you have already initialized the form, you can use the initial property of the field. For example,

 form = CustomForm() form.fields["Email"].initial = GetEmailString() 
+82
May 24 '12 at 10:59 a.m.
source share

If you want to do this in __init__ form for any 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' 
+7
Aug 25 '15 at 11:14
source share

Something like Nigel Cohen will work if you add data to a copy of the collected form dataset:

 form = FormType(request.POST) if request.method == "POST": formcopy = form(request.POST.copy()) formcopy.data['Email'] = GetEmailString() 
+6
Nov 26 '13 at
source share

Just change the 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 
+1
Sep 22 '16 at 12:37
source share

To add another way to the mix: this also works, with slightly more modern notation. It just works around the fact that QueryDict is immutable.

 >>> the_form.data = {**f.data.dict(), 'some_field': 47} >>> the_form['some_field'].as_widget() '<input type="hidden" name="some_field" value="47" class="field-some_field" id="id_some_field">' 
0
Nov 01 '18 at 10:59
source share

If you initialized a form like this

 form = CustomForm() 

then the correct way from January 2019 is to use .initial to replace the data. This will replace the data in the intial text that accompanies the form. This also works if you initialized using some instance, such as form = CustomForm(instance=instance)

To replace the data in the form, you need

 form.initial['Email'] = GetEmailString() 

Summarizing this would be

 form.initial['field_name'] = new_value 
0
Jan 24 '19 at 10:57
source share

Another way to do this is if you have already initialized the form (with or without data), and you need to add additional data before displaying it:

 form = Form(request.POST.form) form.data['Email'] = GetEmailString() 
-12
Apr 04 2018-11-11T00:
source share



All Articles