0

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"?

kbr85
  • 1,416
  • 12
  • 27
  • You should try your first method again, it should be working as intended, maybe the fields name you declaring is wrong https://stackoverflow.com/questions/604266/django-set-default-form-values – Linh Nguyen Sep 22 '20 at 09:55
  • @LinhNguyen The field name is correct. Still not working. – kbr85 Sep 22 '20 at 10:57

1 Answers1

1

To pass a dict into a template script you should use "|safe" filter

<script>
    window.pageData = {{initial|safe}}
</script> 

or you can pass data as json and parse it in your script

Alexey Popov
  • 726
  • 4
  • 8
  • It worked after I turned all values in initial to string. Thanks!! – kbr85 Sep 22 '20 at 11:20
  • It works like this, but it is not the best way. It's better to use json to pass data between js and python to avoid problems with None, True/False values etc. In your case maybe even better to look into form with dynamic fields creation. This will let you use django features to work with forms (cleaning, validation etc). It's not too difficult. You can define fields on the fly in your form class __init__ method – Alexey Popov Sep 23 '20 at 21:42