【问题标题】:Django adding CSS classes to fieldDjango将CSS类添加到字段
【发布时间】: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


【解决方案1】:

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

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

add_error 方法的问题在于它只添加了类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%'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 2011-06-18
    • 2012-02-07
    • 1970-01-01
    • 2011-07-14
    • 2015-06-25
    • 2018-05-31
    相关资源
    最近更新 更多