【发布时间】:2020-12-21 20:23:00
【问题描述】:
如果自定义清理方法检测到错误,我正在尝试将错误类添加到表单集中每个表单的字段。这看起来确实可以解决问题,我加载了页面,并且该字段中确实包含错误类。但是当我在模板中添加自定义过滤器以添加表单控件类时,一切都崩溃了。
# in my inlineformset:
def clean(self, *args, **kwargs):
if any(self.errors):
errors = self.errors
return
## 1) Total amount
total_amount = 0
for form in self.forms:
if self.can_delete and self._should_delete_form(form):
continue
amount = form.cleaned_data.get('amount')
total_amount += amount
if total_amount> 100:
for form in self.forms:
form.fields['amount'].widget.attrs.update({'class': 'error special'})
raise ValidationError(_('Total amount cannot exceed 100%'))
还有,这是我的自定义过滤器代码:
@register.filter(name = 'add_class')
def add_class(the_field, class_name):
''' Adds class_name to the string of space-separated CSS classes for this field'''
initial_class_names = the_field.css_classes() ## This returns empty string, but it should return 'error special'
class_names = initial_class_names + ' ' + class_name if initial_class_names else class_name
return the_field.as_widget(attrs = {'class': class_names,})
而且,在我的模板中:
{# {{ the_field|add_class:"form-control"}} #} #<- This adds the form-control, but removes the other classes added in the clean method
{{ the_field }} {# This shows the two classes for the offending fields, 'error special' #}
我认为问题出在.css_classes() 方法上,它没有引入表单上定义的类。请记住,这些类已在这些字段上设置,并且呈现 {{ the_field }} 显示这些类已正确传递给模板。那么,问题是我是否使用了正确的方法.css_classes() 还是应该使用其他方法?
【问题讨论】:
-
不!在发布我的问题之前,我确实遇到了那个 SO 帖子。我的问题与表单集清理有关,因此
error_css_class不适用于它,因为如果单个表单中的字段有问题,则会设置它。我的模型表单集中的各个表单都很好,但是多个表单的总添加量会触发错误。因此,除非modelformset 有另一个error_css_class,而不是modelform,否则这不适用于我的情况。该帖子中的其他解决方案也已尝试并合并,但问题仍然存在
标签: django