Home > Software design >  Django sign in form, the stylizing with Bootstrap is not doing anything
Django sign in form, the stylizing with Bootstrap is not doing anything

Time:06-11

I am having some troubles with Django. So, I wanted to use Bootstrap´s sign in template and use it in my project. So, I have been able to do it correctly, except the username and password fields, which are showing up as regular {{form.username}} even though I have used the form-control class. Let me show you:

forms.py

from django import forms
from django.forms import TextInput, PasswordInput

class LogINFO(forms.Form):
    username= forms.CharField(label= 'Usuario: ', max_length=20, widget=forms.TextInput(attrs={"placeholder": "Username", 'style': 'width: 300px;', "class": "form-control"}))
    password=forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'style': 'width: 300px;', 'class': 'form-control'}))

and my login.html

{% csrf_token %}
            <div >

                {{form.username}}

            </div>
            <div >
                {{form.password}}

            </div>

Well, it apparently omits everything and it just shows up as a regular form input. I am not using model as I am using the auth application.

CodePudding user response:

Authentication forms like login have a tendency to override customisations unless set up in a particular way.

Try the following

urls.py

from django.contrib.auth import views
from .forms import LogINFO
....
    path('login/',
    views.LoginView.as_view(
        template_name="registration/login.html", #this is default, change as needed
        authentication_form=LogINFO,
        ),
    name='login'
),

views.py

from django.contrib.auth.forms import AuthenticationForm,

class LogINFO(AuthenticationForm):
    username= forms.CharField(label= 'Usuario: ', max_length=20, widget=forms.TextInput(attrs={"placeholder": "Username", 'style': 'width: 300px;', "class": "form-control"}))
    password=forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'style': 'width: 300px;', 'class': 'form-control'}))
    def __init__(self, *args, **kwargs):
        super(LogINFO, self).__init__(*args, **kwargs) 

The key elements are:

  • making your form a subclass of the AuthenticationForm class (which makes sense as you are using Django's auth)
  • calling the super init function (which allows the subclass to use all the methods of the class)
  • and providing the class of the authentication_form in your URLs.py file

One final note, when I am overriding a template for another app like django.config.auth, I place the app in question before it in settings.py INSTALLED_APPS so that it finds my new template first.

  • Related