UpdateView和CreateView共享通用的JavaScript函数

时间:2016-06-15 07:42:07

标签: django django-views

Django 1.9.7

更新和创建或多或少类似的操作。有时我想将JavaScript事件添加为widget attrs。例如,用户选择性别。取决于我想显示或隐藏婚前姓名。这只是UpdateView和CreateView常见的一些操作的一个示例。

我尝试将其组织为mixin,但失败了:UpdateView和CreateView都使用FormMixin。如果我组织另一个继承自FormMixin的mixin,我会发生冲突。

你可以帮我理解如何在不重复代码的情况下应对吗?

class PersonUpdateView(UpdateView):
    model = Person
    fields = ['gender', 'last_name']

class PersonCreate(CreateView):
    model = Person
    fields = ['gender', 'last_name']
    redirect_name = "people"

    field_attrs = {'gender':  {'onchange':"alert('G')"},
                   'last_name': {'onclick': "alert('LN')"},
                   }     

    def get_form(self, form_class=None):
        form = super(PersonCreate, self).get_form(form_class)
        for key, value in self.field_attrs.items():
            form.fields[key].widget.attrs = value;
        return form

1 个答案:

答案 0 :(得分:0)

你的mixin应该是一个简单的类:

class CreateUpdateMixin(object):

    model = Person
    fields = ['gender', 'last_name']

    field_attrs = {'gender':  {'onchange':"alert('G')"},
                   'last_name': {'onclick': "alert('LN')"},
                   }

然后你就这样使用它:

class PersonUpdateView(CreateUpdateMixin, UpdateView):
    pass

class PersonCreate(CreateUpdateMixin, CreateView):
    redirect_name = "people"   

    def get_form(self, form_class=None):
        form = super(PersonCreate, self).get_form(form_class)
        for key, value in self.field_attrs.items():
            form.fields[key].widget.attrs = value;
        return form