riderken
riderken

Reputation: 99

how do I style and align errorlist from django forms?

This form errorfield comes with ul and li elements and I can't find a way to change it. So is it possible to have "email is taken" as error instead of having the whole ul element "email" before that, if that's not possible then can we at least align it inline together the ul and li. Thx in advance.

css

.errorlist li {
    list-style-type: none;
    display: inline-block;
}

.account-errors {
  font-family: "Circular Std Book";
  color: black;
}

html

      {% if form.errors %}
        <div class="account-errors">
          <div class="container-error">
            {{ form.errors }}
          </div>
        </div>
      {% endif %}

what it looks like

Inspect element view

Upvotes: 1

Views: 849

Answers (1)

JSRB
JSRB

Reputation: 2613

According to the official documentation, you can pass an individual error class to the form instance on construction like so:

# forms.py

from django.forms.utils import ErrorList

class DivErrorList(ErrorList):
     def __str__(self):
         return self.as_divs()

     def as_divs(self):
         if not self: return ''
         return '<div class="your_css_class">%s</div>' % ''.join(['<div 
               class="your_css_class">%s</div>' % e for e in self])

Now in your view you could do s.th. like

# views.py

# Initiate form instance and pass the custom error_class
my_form = ContactForm(data, auto_id=False, error_class=DivErrorList)

...
# CSS

.your_css_class {
    font-size: 2em;
}

Upvotes: 1

Related Questions