微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django将CSS类添加到字段

如何解决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()还是应该使用其他方法

解决方法

我能够使用表单的.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%'))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?