1

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!

mharre
  • 233
  • 3
  • 17

1 Answers1

0

You can write a class CustomForm which derives from AuthenticationForm and work on it.

You can also enforce fields to use your desired widget instead of default widget by using widget keyword argument like below:

<A field> =  forms.<A Field>(widget = <A Widget>(attrs = {'class': 'form-control' })
  

   
ariaman5
  • 132
  • 1
  • 8
  • 1
    But then wouldn't I have to also add all of the logic for authentication, password check etc if I created a custom form? I'd prefer to not have to do that personally, if possible though haha. I simply those classes into the input fields of the already generated form – mharre Jun 16 '21 at 09:55
  • @mharre It derives from Authentication form which handles all those stuff you said. See this https://docs.djangoproject.com/en/3.2/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm – ariaman5 Jun 16 '21 at 10:46
  • yes thank you! I experimented a bit on my own based on a bunch of google searches and was able to figure it out by extending the base class form as you mentioned. – mharre Jun 16 '21 at 11:10
  • @mharre you're welcome. Accept my answer then. :) – ariaman5 Jun 16 '21 at 19:34