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

I would like to create widgets that add specific classes to the markup of elements when the corresponding field has errors.

I find it difficult to find information on how to check whether a field is associated with this message from the widget definition code.

At the moment, I have the following stub widget code (the last 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 some light on a reasonable way to fill in the field_has_errors Boolean here? (or perhaps suggest a better way to accomplish what I'm trying to do). Thanks in advance.

+7
django django-forms django-widget
source share
2 answers

According to Jason, the widget does not have access to the field itself. I believe the best solution 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 what you need.

+9
source share

The widget does not know the field to which it is applied. This is the field in which error information is stored. You can check error_messages in the init method of your form and add the error class to your widget accordingly:

 class YourForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(YourForm, self).__init__(*args, **kwargs) attrs = {} if self.fields['your_field'].error_messages is not None: attrs['class'] = 'errors' self.fields['your_field'].widget = YourWidget(attrs=attrs) 
+3
source share

All Articles