Search code examples
djangodjango-formsdjango-widget

Django: How to check if there are field errors from within custom widget definition?


I'd like to create widgets that add specific classes to element markup when the associated field has errors.

I'm having a hard time finding information on how to check whether a field has errors associated with it, from within widget definition code.

At the moment I have the following stub widget code (the final widget will use more complex markup).

from django import forms
from django.utils.safestring import mark_safe
class CustomTextWidget(forms.Widget):
        def render(self, name, value, attrs):
            field_has_errors=False # change to dynamically reflect field errors, somehow
            if field_has_errors:
                error_class_string="error"
            else:
                error_class_string="" 
            return mark_safe(
            "<input type=\"text\" class=\"%s\" value=\"%s\" id=\"id_%s\" name=\"%s\">" % (error_class_string, value, name, name)
            )

Can anyone shed light on a sensible way to populate the field_has_errors Boolean here? (or perhaps suggest a better way to accomplish what I'm trying to do). Thanks in advance.


Solution

  • As Jason says, the widget has no access to the field itself. I think a better solution though is to use the cascading nature of CSS.

    {% for field in form %}
    <div class="field{% if field.errors %} field_error{% endif %}">
    {{ field }}
    </div>
    {% endfor %}
    

    Now in your CSS you can do:

    div.field_error input { color: red }
    

    or whatever you need.