Django generates error_class

Is there a way to provide the form with a special error rendering function in the form definition? In the documents under customizing-the-error-list-format, it shows how you can provide a form with a special error rendering function, but it seems that you should declare it when you create the form, and not when you define it.

So you can define some ErrorList class, for example:

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 this error_class file:

  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 an error class every time I create a form, is there a way to define a custom error renderer inside the form definition?

+4
source share
2 answers

If you want this behavior to be common to all your forms, you could define your own base form class:

 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 you have all the subclasses of your form. Then your whole form will have a DivErrorList as the default error rendering tool, and you can still change it with 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) 
+6
source

Try the following:

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

Must work. But I did not test it.

+3
source

Source: https://habr.com/ru/post/1299220/


All Articles