How can I change form field values after calling the is_valid() method?
Save the model form with commit=False
, then modify the instance before saving to the database.
if form.is_valid() and form1.is_valid():
instance = form1.save(commit=False)
instance.uid = '12134324231'
instance.save()
If form1
had any many-to-many relationships, you would have to call the save_m2m
method to save the many-to-many form data. See the docs for full details.
From Overriding clean() on a ModelFormSet.
Also note that by the time you reach this step, individual model instances have already been created for each Form. Modifying a value in form.cleaned_data is not sufficient to affect the saved value. If you wish to modify a value in ModelFormSet.clean() you must modify form.instance:
from django.forms import BaseModelFormSet
class MyModelFormSet(BaseModelFormSet):
def clean(self):
super(MyModelFormSet, self).clean()
for form in self.forms:
name = form.cleaned_data['name'].upper()
form.cleaned_data['name'] = name
# update the instance value.
form.instance.name = name
So what you should do is:
if form.is_valid() and form1.is_valid():
form1.instance.uid ='12134324231'
form1.save()