您可以添加自定義屬性在你的領域形式的元定義與小部件。
class SomeForm(forms.ModelForm):
class Meta:
model = SomeModel
widgets = {'field_name1': forms.Textarea(attrs={'data-bind':'value: field1'}),
'field_name2': forms.TextInput(attrs={'data-bind':'value: field2'})}
例如,第一場將呈現:
<textarea id="id_field_name1" name="field_name1" data-bind="value: field1"></textarea>
更新: 這裏獎金是一個簡單的方法來改變每個字段屬性的形式,例如,如果他們都需要特定類的(其他的js插件或CSS樣式有用)
def __init__(self, *args, **kwargs):
super(SomeForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs['class'] = 'some_form_field'
# this could be used in your case if the Django field name is the
# same as the KO.js field name
field.widget.attrs['data-bind'] = 'value: %s' % name