Search code examples
djangodjango-formsdjango-widget

Why widget EmailInput style doesn't apply


I'm trying to style the django forms, I could apply the class to the TextInputs with widget but for the email and password it doesn't apply. Any idea why? Also, how can I delete the text above password? The password requisites, it isn't help_text

forms.py

class SignupForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['email', 'first_name', 'last_name', 'password1', 'password2']
        widgets = {
            'email': forms.EmailInput(attrs={'class': 'forms-group__input'}),
            'first_name': forms.TextInput(attrs={'class': 'forms-group__input'}),
            'last_name': forms.TextInput(attrs={'class': 'forms-group__input'}),
            'password1': forms.PasswordInput(attrs={'class': 'forms-group__input'}),
            'password2': forms.PasswordInput(attrs={'class': 'forms-group__input'}),

        }

forms.html

        <form class="forms-group__form" method="POST" enctype="multipart/form-data">
    
        {% csrf_token %}
        {% for field in form %}
            {{ field.errors }} <br>
            <div class="forms-group__input-field">
    
                <label class="forms-group__label">{{ field.label_tag }}</label><br>
    
                {{ field }}<br>
    
                {% if field.help_text %}
                <p class="help">{{ field.help_text|safe }}</p>
                {% endif %}
    
            </div>
        {% endfor %}

    <div class="forms-group__button-div"><input class="button submit-button forms-group__button" type="submit" value="Update Profile"></div>

    </form>

enter image description here


Solution

  • Fields that are declared in the form class are not automatically generated by the ModelForm, hence declaring a widget for them in the widgets attribute of the Meta does not work. You can either forego declaring it in the class and let it be generated automatically:

    class SignupForm(UserCreationForm):
        email = forms.EmailField()
        ...
    

    Or you can specify the widget for the field in the field itself:

    class SignupForm(UserCreationForm):
        email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'forms-group__input'}))
        ...