如何在django中使用带有modelForm的自定义ErrorList类?

时间:2014-05-13 14:43:15

标签: django forms django-class-based-views

我写了一个自定义ErrorList类:

class jQueryUiErrors(ErrorList):
def __unicode__(self):
    return self.as_divs()
def as_divs(self):
    if not self:
        return ''
    return '<div class="ui-state-error ui-corner-all">%s</div>' % ''.join(['<div class="error"><span style="float: left; margin-right: .3em;" class="ui-icon ui-icon-alert"></span>%s</div>' % e for e in self])

但无法让它发挥作用。我试过了:

class ClientForm(ModelForm):
def __init__(self, *args, **kwargs):
    kwargs_new = {'error_class': jQueryUiErrors}
    kwargs_new.update(kwargs)
    super(ClientForm, self).__init__(*args, **kwargs_new)
class Meta:
    model = Client
    fields = ['first_name', 'last_name', 'owner', 'source', 'contact_status', 'next_contact']

class ClientForm(ModelForm):
def __init__(self, *args, **kwargs):
    self.error_class = jQueryUiErrors
    super(ClientForm, self).__init__(*args, **kwargs)

但没有任何影响 - 错误保持在那里,呈现为列表

我在CreateWithInlinesView中使用它,它基于CreateView,如果它与任何事情有关。

PS第二个问题:我可以更改默认的error_class项目范围,以使用我的类格式化所有错误吗?

1 个答案:

答案 0 :(得分:0)

你只需做一些重新安排:

class ClientForm(ModelForm):
    def __init__(self, *args, **kwargs):
        kwargs.update({'error_class': jQueryUiErrors})
        super(ClientForm, self).__init__(*args, **kwargs)
    class Meta:
        model = Client
        fields = ['first_name', 'last_name', 'owner', 'source', 'contact_status', 'next_contact']

或者:

class ClientForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ClientForm, self).__init__(*args, **kwargs)
        self.error_class = jQueryUiErrors