用django形式使用knockout.js? [英] using knockout.js with django forms?

查看:150
本文介绍了用django形式使用knockout.js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找添加一些结构到我的客户端代码,并已阅读关于 knockout.js 。我一直在阅读文档,并提出一个简单的问题 - 由于敲除需要用户向html元素添加一个 data-bind 属性,最好的方法是它使用 django 表单,因为目前我使用 {{form.as_p}}

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 }}

我很好奇我应该如何以及在哪里应用到视图模型(如果它是Django中的字段,或者是没收 {{form.as_p}} 并输入html。

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.

推荐答案

p>您可以在窗体的Meta定义中添加自定义属性到窗口部分。

You can add custom attributes to your fields in the Form's Meta definition with widgets.

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'})}

例如,第一个字段将被呈现:

For example, the first field would be rendered:

<textarea id="id_field_name1" name="field_name1" data-bind="value: field1"></textarea>

更新:
作为奖励这里是一个简单的方法更改表单中每个字段的属性,例如,如果他们都需要一个特定的类(对其他js插件或CSS样式有帮助)

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)

    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

这篇关于用django形式使用knockout.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆