2014-03-06 35 views

回答

1

编辑来回答更准确。

如果要指定错误或必填字段类:

class MyForm(Form): 
    error_css_class = 'error' #here you can set this to 'invalid' 
    required_css_class = 'required' 

裁判:

myfield= forms.CharField(attrs={'class': 'myclass'}) 

裁判:https://docs.djangoproject.com/en/1.6/ref/forms/api/

您也可以改变你的类一个场:https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

+0

我知道这个解决办法,但我需要在验证过程中 – user3387113

+1

添加类只有在这个领域有错误[答案是正确的(https://docs.djangoproject.com/en/1.6/ref/forms/api /#django.forms.Form.error_css_class):*“Form类有几个钩子可用于将类属性添加到所需的行或错误的行”* – danihp

0

在你的表格中干净的方法d您可以更新所有错误的字段的小部件的attrs,以实现与您想要的类似的功能。

from django import forms 

class MyForm(forms.Form): 
    myfield = forms.CharField() 

    def clean(self): 
     if 'myfield' in self._errors: 
      self.fields['myfield'].widget.attrs.update({'class': 'invalid'}) 

     # Or to add the class to the input of all erroring fields: 
     for field in self.fields: 
      if field in self._errors: 
       self.fields[field].widget.attrs.update({'class': 'invalid'}) 

     return super(MyForm, self).clean() 
相关问题