首页 > 解决方案 > Django将CSS类添加到字段

问题描述

如果自定义清理方法检测到错误,我正在尝试将错误类添加到表单集中每个表单的字段。这看起来确实可以解决问题,我加载了页面,并且该字段中确实包含错误类。但是当我在模板中添加一个自定义过滤器来添加一个表单控件类时,一切都崩溃了。

# 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()还是应该使用另一种方法?

标签: django

解决方案


我能够使用.add_error表单的方法将类错误添加到字段中。虽然这可以解决这个问题,但如果有人能解释 the_field.css_classes() 如何返回一个空字符串而不是 clean 方法中设置的字符串,我仍然会很感激:

form.fields['amount'].widget.attrs.update({'class': 'error special'})

add_error 方法的问题在于它只添加了 class error。但是,如果我想向special小部件添加另一个类怎么办?所以,原来的问题还需要一个答案。我在这里的解决方案只是一个解决方案而不是解决方案:

# 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:
        msg = 'This field throw the amount over the 100% limit'
        form.add_error('amount', msg)

if total_amount> 100:
    raise ValidationError(_('Total amount cannot exceed 100%'))

推荐阅读