开发者

django forms error_class

开发者 https://www.devze.com 2022-12-17 03:41 出处:网络
Is there a way to give a form a special error rendering function in the form definition? In the docs under customizing-the-error-list-format it shows how you can give a form a special error rendering

Is there a way to give a form a special error rendering function in the form definition? In the docs under customizing-the-error-list-format it shows how you can give a form a special error rendering function, but it seems like you have to declare it when you instantiate the form, not when you define it.

So you can define so开发者_Python百科me ErrorList class like:

from django.forms.util import ErrorList
 class DivErrorList(ErrorList):
     def __unicode__(self):
         return self.as_divs()
     def as_divs(self):
         if not self: return u''
         return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])

And then when you instantiate your form you can instantiate it with that error_class:

 f = ContactForm(data, auto_id=False, error_class=DivErrorList)
 f.as_p()

<div class="errorlist"><div class="error">This field is required.</div></div>
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
<p>Message: <input type="text" name="message" value="Hi there" /></p>
<div class="errorlist"><div class="error">Enter a valid e-mail address.</div></div>
<p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p>
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>

But I don't want to name the error class every time I instantiate a form, is there a way to just define the custom error renderer inside the form definition?


If you want this behaviour to be common to all your forms, you could have your own form base class defined like that :

class MyBaseForm(forms.Form):
    def __init__(self, *args, **kwargs):
        kwargs_new = {'error_class': DivErrorList}
        kwargs_new.update(kwargs)
        super(MyBaseForm, self).__init__(self, *args, **kwargs_new)

And then have all your form subclass that one. Then all your form will have DivErrorList as a default error renderer, and you will still be able to change it using the error_class argument.

For ModelForm's:

class MyBaseModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        kwargs_new = {'error_class': DivErrorList}
        kwargs_new.update(kwargs)
        super(MyBaseModelForm, self).__init__(*args, **kwargs_new)


Try the following:

class MyForm(forms.Form):
    ...

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.error_class = DivErrorList

Should work. But I did not test it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号