I have a form in a Django web site. When the form is shown, I create a new field using jQuery. Something like:
$("#field_defined_in_form").after(
'<input class="numberinput" type="number" step="1" id="id_new_field" name="new_field">'
)
I can save the information provided in "#id_new_field"
to the database with POST. However, when I want to edit the information in the DB, I need to provide the initial value for "#id_new_field"
.
1 - How can I provide the initial value for a form field that will be created using Jquery?
I tried:
initial = {
'new_field': 'Initial_value',
}
form = TheFormClass(initial=initial)
But this does not work.
2 - Is there any way to access the form initial values using jQuery? I guess not, but I ask just in case.
I could also pass the value to jQuery through the template like:
<script>
window.pageData = {
new_field : '{{new_field_value}}',
}
</script>
The real life problem includes a non-fixed number of new_field
so I tried to pass the whole initial dict.
<script>
window.pageData = {
initial : '{{initial}}',
}
</script>
This does not work because initial is turned into a string not an object. So:
3 - How can I pass the python dict initial to a jQuery object, so I can access initial['new_field'] in jQuery and set the initial value for "#id_new_field"
?