Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django forms error_class

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 some 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?

like image 336
Purrell Avatar asked Dec 30 '22 04:12

Purrell


1 Answers

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)
like image 190
Clément Avatar answered Jan 15 '23 02:01

Clément