Django 1.9添加一个类来形成标签

时间:2016-09-22 16:45:46

标签: python django django-forms django-templates django-1.9

在我的forms.py文件中,我重新配置了UserForm类的__init__函数以包含一个css类。不幸的是,这样做只允许我向<input>而不是<label>添加一个类。如何在标签中添加一个类?

这是我的forms.py文件:

class UserForm(forms.ModelForm):
    # password = forms.CharField(widget=forms.PasswordInput())
    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        self.fields['email'].widget.attrs = {
            'class': 'form-control'
        }

    class Meta:
        model = User
        fields = ('email',)

    def clean_email(self):
        email = self.cleaned_data['email']
        if not email:
            raise forms.ValidationError(u'Please enter an email address.')
        if User.objects.exclude(pk=self.instance.pk).filter(email=email).exists():
            raise forms.ValidationError(u'Email "%s" is already in use.' % email)
        return email

谢谢!

1 个答案:

答案 0 :(得分:-2)