Search code examples
cssdjangodjango-formsdjango-widget

using widgets to change the CSS of label in Django forms


I am trying to apply CSS styling to the admin login form in Django (version 3.1.3). I am able to customise the inputs easily enough using Widgets via the forms.TextInput(attrs={'class':'textinputclass'}) method however there seems to be no way to add CSS class to the labels? I can set the label to "false" so that it doesnt show up at all, but ideally I would like to be able to associate a CSS class to it.

My code below shows the widgets being used for the text input for username and password. How do I do something similar for the label?

class MyAuthForm(AuthenticationForm):
    class Meta:
        model = Lesson
        fields = ['username', 'password']

    def __init__(self, *args, **kwargs):
        super(MyAuthForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget = forms.TextInput(attrs={'class': 'input', 'placeholder': 'Username'})
        self.fields['username'].label = False
        self.fields['password'].widget = forms.PasswordInput(attrs={'class': 'input', 'placeholder': 'Password'})
        self.fields['password'].label = False

Solution

  • This is straightforward to do if you don't mind separately rendering out the label. I haven't found an easier way to do it yet myself.

    In the template:

    {% for field in form %}
            <label class="label-class">{{ field.label }}</label>
            {{ field }}
        {% endfor %}
    

    A field's label in the template will render the field's name by default. If you want to set a specific label, you have to pass it into the field rather than the widget:

    username = forms.CharField(max_length=254, label='Username', widget=forms.TextInput(
            attrs={
            'class': 'input',
            'placeholder': 'username',
            }
        ))
    

    Further reading: How to set css class of a label in a django form declaration?