ModelForm and error_css_class

Question:

my problem is simple. Where the right place for a custom error_css_class value is when using ModelForm?

I tried this:

class ToolForm(ModelForm):
error_css_class = 'wrong_list'
class Meta:
    model = Tool
    widgets = {
               'name' : TextInput(attrs={'class': 'small_input corners'}),
               'description' : Textarea(attrs={'cols': 20, 'rows': 5, 'class': 'text corners'}),
               'stocks' : TextInput(attrs={'class': 'small_input corners'}),
               'state' : Textarea(attrs={'cols': 25, 'rows': 6, 'class': 'text corners'}),
    }

Also, I tried as a class Meta value. Doesn’t work either.

By now I just changed my css to ‘errorlist’ (u know, the default one), buuut this kind of doubts make me unhappy :P.

Any help is appreciated.

Asked By: Alex Pi

||

Answers:

You can define your own error list class by inherting from django’s ErrorList. See the docs for details:

Note that you’ll have to override the method to output the full HTML and can’t just replace CSS class. You could call the base method and do a string replace on “class=”errolist”” and return the output.

Answered By: ars

create custom class thath extends ErrorList

class CustomErrorList(ErrorList):
    def get_context(self):
        return {
            "errors": self,
            "error_class": "your css class",
        }

And add it in your form class:

class CustomForm(ModelForm):
def init(self, *args, **kwargs):
super().init(*args, **kwargs)
self.error_class = CustomErrorList

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.