I am relatively new to django and want to customize the AuthenticationForm but an not sure how to do it. I essentially want to override the init function to be able to inject attributes and control what is displayed on the form. Specifically I would like to add this for my login form:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].widget = forms.widgets.TextInput(attrs={
'class': 'form-control'
})
self.fields['password1'].widget = forms.widgets.PasswordInput(attrs={
'class': 'form-control'
})
My issue is that I let django do all of the work for me when creating my login view/form therefore I am unsure how to customize it. Reading the docs the LoginView uses the default AuthenticationForm.
Any help is greatly appreciated!
EDIT: Figured it out in case anyone else reads this from Google
urls.py for my project (added the accounts/login/ and 2 imports) -
from django.contrib.auth.views import LoginView
from blog.forms import MyAuthenticationForm
path('accounts/login/', LoginView.as_view(authentication_form=MyAuthenticationForm)),
path('accounts/', include('django.contrib.auth.urls'))
Then I created my own form but extended the AuthenticationForm like so:
class MyAuthenticationForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].widget = forms.widgets.TextInput(attrs={
'class': 'form-control'
})
self.fields['password'].widget = forms.widgets.PasswordInput(attrs={
'class': 'form-control'
})
Now everything works perfectly!