Rendering required and error classes with Django Forms fields in a custom template

I need to display the necessary attributes and errors as part of the markup using a field in the template. I know that this can be done using form.as_p etc. when the layout is automatically generated.

However, I have a complex two-column layout for the form. Is it possible to include required_css_class = 'required' , which is part of the form class, spitting out html for individual fields?

I need to do this because I want to control jquery validation from generated html without extra work.

thanks

+4
source share
1 answer

required_css_class apparently used by forms.BoundField.css_classes and forms.BaseForm._html_output , which is only for as_p , as_table , etc.

This is not part of the usual rendering of widgets.

You can use the same css_classes method to return classes for your element, so I think the easiest solution would be to wrap the <input> element and specify the class {{ field.css_classes }} and change your validation selector.


Alternatively, here you can crack the error class into error fields:

  def __init__(self, *args, **kwargs): super(form, self).__init__(*args, **kwargs) for field in self.errors: if not field == '__all__': # errors dict can have key __all__ for non field errors. self.fields[field].widget.attrs['class'] = \ self.fields[field].widget.attrs.get('class', '') + 'error' 

To use required_css_class , you will need to use the BoundField.css_classes method, which includes hacking the __getitem__ and __iter__ base forms as the BoundField is created on demand. The above method is simpler.

+7
source

Source: https://habr.com/ru/post/1344098/


All Articles