I am looking to add some structure to my client side code and have been reading about knockout.js
. I have been reading the documentations and have a simple question to ask - since knockout requires the user to add a data-bind
attributes to the html elements, what is the best way for it to work with django
forms, since currently I am using {{ form.as_p }}
I am curious how and where should I form's inputs to the view model
(if it is in the form fields in Django, or forfeiting {{ form.as_p }}
and type out in html instead.
You can add custom attributes to your fields in the Form's Meta definition with widgets.
For example, the first field would be rendered:
Update: as a bonus here is an easy way to change an attribute for every field in a form, for example if they all need a specific class (helpful for other js addons or css styling)
Another way is to use django-crispy-forms and define
data-bind
attributes in the layout:Then in the template you only do:
and voila.
Cripsy-forms is even more powerful than that and allows you to define your own layout templates etc.