Iterating through form.non_field_errors is not always the best approach, for instance in my case I wanted to display a tooltip like in this screenshot next to the field in question using Django Widget Tweaks.
project/app/templates/template.html
{% render_field field class="form-control is-invalid" data-toggle="tooltip" title=field.errors.as_text %}
Instead of messing around with template code to pass the HTML title attribute in one piece I followed the tip from @oblalex and wrote my own modified ErrorList class with a as_text method without asterisks.
project/app/utils.py
from django.forms.utils import ErrorList
class MyErrorList(ErrorList):
"""
Modified version of the original Django ErrorList class.
ErrorList.as_text() does not print asterisks anymore.
"""
def as_text(self):
return '\n'.join(self)
Now that the as_text() function is overwritten, you can pass your class MyErrorList as the error_class argument of your Form or ModelForm or like in my case some ModelForm formset:
project/app/views.py
from django.forms import formset_factory
from .forms import InputForm
from .utils import MyErrorList
def yourView(request):
InputFormSet = formset_factory(InputForm)
formset = InputFormSet(error_class=MyErrorList)
context = {'formset': formset}
return render(request, 'template.html', context)
And now the tooltip looks like this without the asterisk.
Instead of passing the error_class every time you instantiate a form in your views, you can just add this one-liner to your form class (see this answer from @Daniel):
project/app/forms.py
from django import forms
from .utils import MyErrorList
class InputForm(forms.ModelForm):
def __init__(self, *args, row, **kwargs):
super(InputForm, self).__init__(*args, **kwargs)
self.error_class = MyErrorList