0

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
大陸北方網友
  • 3,696
  • 3
  • 12
  • 37
Ramirez100
  • 17
  • 1
  • 8

1 Answers1

4

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?

twrought
  • 636
  • 5
  • 9
  • Thanks, that works slightly but I dont understand how to integrate it with the form submission when using {% csrf_token %} {{ form.as_p }} – Ramirez100 Jan 15 '21 at 11:34
  • @Ramirez100 can you explain more of what your issue is with submitting the form? You can post some code as well! – twrought Jan 15 '21 at 22:43
  • I got it working now. My issue was the code provided by you listed out the form as well as the formatted label. I was looking to just provide a class to the label as the form was being created later. I changed your code to this {% for field in form %} {% endfor %} That worked perfectly for applying css class. As a follow up question, do you know how to target a specific label so that certain labels get different css classes? – Ramirez100 Jan 16 '21 at 01:06
  • As you can see from the above comments. I am struggling to highlight code in comments – Ramirez100 Jan 16 '21 at 01:13
  • @Ramirez100 no worries! When you want a codeblock, just hit enter, and wrap your code three in tick marks ( ```) on either side. – twrought Jan 16 '21 at 01:29