0

In my forms.py file I reconfigured the class UserForm's __init__ function to include a css class. Unfortunately doing this only allowed me to add a class to the <input> and not the <label>. How can I add a class to the label as well?

Here is my forms.py file:

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

Thanks!

karthikr
  • 97,368
  • 26
  • 197
  • 188
Lefty
  • 425
  • 1
  • 5
  • 19
  • can you not target this form element from an external css file ? – karthikr Sep 22 '16 at 16:47
  • Possible duplicate of [Add class to Django label\_tag() output](http://stackoverflow.com/questions/414679/add-class-to-django-label-tag-output) – vishes_shell Sep 22 '16 at 16:48
  • Possible duplicate of http://stackoverflow.com/questions/6959178/how-to-set-css-class-of-a-label-in-a-django-form-declaration You could do something like this:
    {% for field in form %} {{ field }} {% endfor %}
    – Edyoucaterself Sep 28 '16 at 13:08

1 Answers1

-3

Look at Django Widget Tweaks.