如果此字段无效,如何将自己的类添加到字段中?
例如,如果此字段无效,我会添加class="invalid"
形式:
class MyForm(forms.Form):
myfield = forms.CharField()
模板:
{{ form.myfield }}
答案 0 :(得分:1)
编辑更准确地回答。
如果要为错误或必填字段指定类:
class MyForm(Form):
error_css_class = 'error' #here you can set this to 'invalid'
required_css_class = 'required'
参考:https://docs.djangoproject.com/en/1.6/ref/forms/api/
您还可以使用以下内容更改一个字段的类
myfield= forms.CharField(attrs={'class': 'myclass'})
参考:https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs
答案 1 :(得分:0)
在表单清理方法中,您可以为所有错误的字段更新小部件的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()