Tuesday, July 31, 2012

Changing values populated to a form (works for unbound ModelForms and Forms only)


http://stackoverflow.com/questions/813418/django-set-field-value-after-a-form-is-initialized

The asker's scenario:


I am trying to set the field to a certain value after the form is initialized.
For example, I have the following class.



####################



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





##############################
Only the first method -- unbound form constructed, then the initial data passed in or set using field.initial -- works in populating the field.

If after is_valid() is called, it doesn't work to populate the field shown in the browser to the user:
what this does is just change the value inside the cleaned_data dict in your view. (for internal ss-processing, perhaps.)











No comments:

Post a Comment