Commits

Trey Hunner  committed 5cb3b29

Add render_field support for error/required class

  • Participants
  • Parent commits b9c66bc

Comments (0)

Files changed (2)

File widget_tweaks/templatetags/widget_tweaks.py

 
     def render(self, context):
         bounded_field = self.field.resolve(context)
+        field = getattr(bounded_field, 'field', None)
+        if (getattr(bounded_field, 'errors', None) and
+            'WIDGET_ERROR_CLASS' in context):
+            bounded_field = append_attr(bounded_field, 'class:%s' %
+                                        context['WIDGET_ERROR_CLASS'])
+        if field and field.required and 'WIDGET_REQUIRED_CLASS' in context:
+            bounded_field = append_attr(bounded_field, 'class:%s' %
+                                        context['WIDGET_REQUIRED_CLASS'])
         for k, v in self.set_attrs:
             bounded_field = set_attr(bounded_field, '%s:%s' % (k,v.resolve(context)))
         for k, v in self.append_attrs:

File widget_tweaks/tests.py

     date = forms.DateField(widget=SelectDateWidget(attrs={'egg': 'spam'}))
 
 
-def render_form(text, form=None):
+def render_form(text, form=None, **context_args):
     """
     Renders template ``text`` with widget_tweaks library loaded
     and MyForm instance available in context as ``form``.
     """
     tpl = Template("{% load widget_tweaks %}" + text)
-    context = Context({'form': MyForm() if form is None else form})
+    context_args.update({'form': MyForm() if form is None else form})
+    context = Context(context_args)
     return tpl.render(context)
 
 
         assertIn('class="class0"', res)
 
 
+class RenderFieldWidgetClassesTest(TestCase):
+    def test_use_widget_required_class(self):
+        res = render_form('{% render_field form.simple %}',
+                          WIDGET_REQUIRED_CLASS='required_class')
+        self.assertIn('class="required_class"', res)
+
+    def test_use_widget_error_class(self):
+        res = render_form('{% render_field form.simple %}', form=MyForm({}),
+                          WIDGET_ERROR_CLASS='error_class')
+        self.assertIn('class="error_class"', res)
+
+    def test_use_widget_error_class_with_other_classes(self):
+        res = render_form('{% render_field form.simple class="blue" %}',
+                          form=MyForm({}), WIDGET_ERROR_CLASS='error_class')
+        self.assertIn('class="blue error_class"', res)
+
+    def test_use_widget_required_class_with_other_classes(self):
+        res = render_form('{% render_field form.simple class="blue" %}',
+                          form=MyForm({}), WIDGET_REQUIRED_CLASS='required_class')
+        self.assertIn('class="blue required_class"', res)
+
+
 class RenderFieldTagFieldReuseTest(TestCase):
     def test_field_double_rendering_simple(self):
         res = render_form('{{ form.simple }}{% render_field form.simple foo="bar" %}{% render_field form.simple %}')