Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 470
bitbutter Avatar asked Jul 09 '10 14:07

bitbutter


People also ask

What is the significance of introducing custom widgets in Django?

The widget in Django will handle the rendering of the HTML elements and extract data from a POST/GET dictionary that corresponds to the same widget. Whenever we specify a field on a Django form, Django uses some default widget appropriate to the data type to be displayed.

What is Attrs Django?

attrs . A dictionary containing HTML attributes to be set on the rendered DateInput and TimeInput widgets, respectively. If these attributes aren't set, Widget. attrs is used instead.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.

Which code will give us a textarea form field in Django?

CharField() is a Django form field that takes in a text input. It has the default widget TextInput, the equivalent of rendering the HTML code <input type="text" ...> .


2 Answers

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.

like image 166
Daniel Roseman Avatar answered Oct 11 '22 13:10

Daniel Roseman


The widget has no knowledge of the field to which it is being applied. It is the field that maintains information about errors. You can check for error_messages in the init method of your form, and inject an 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)
like image 24
Jason Leveille Avatar answered Oct 11 '22 13:10

Jason Leveille