Search code examples
cssdjangodjango-authentication

How to apply specific css to Django login form


Here is the code of that form:

<div>
<h2>Login here</h2>
    <form method="post">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Login</button>
    </form>
</div>

This form comes from django.contrib.auth


Solution

  • You can assign both HTML ID and classes to your form fields using the widget attributes. I put an example below of setting both the ID and class, but be careful with the ID's because Django auto creates them. The ID and class names must match your CSS file of course.

    class MyForm(forms.ModelForm):
    
        class Meta:
            model = User
            fields = ('email', 'password')
            # Set custom ID and class for password field.
            widgets = {'password': forms.PasswordInput(attrs={'id': 'my_HTML_id', 'class': 
                       'my_HTML_class'})}