Search code examples
pythonpython-3.xdjangodjango-viewsdjango-forms

How to resolve TypeError: __init__() got an unexpected keyword argument 'attrs' Django


I'm working on Django forms however I'm getting this error

TypeError: init() got an unexpected keyword argument 'attrs'

So what I do not understand is I get the error only when I include the email and the two passwords fields and this really does not make sense to me hence I fail to fix this error can I please get help to understand what is actually happening here and what is causing this error.

CODE BELOW: forms.py

from django import forms
from phonenumber_field.formfields import PhoneNumberField



class UserAccount(forms.Form):

    name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control',     'placeholder':'First Name'}))
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Surname'}))
    phone = PhoneNumberField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number'}))
    email = forms.CharField(widget=forms.EmailField(attrs={'class':'form-control', 'placeholder':'Email'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'}))
    verify_password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'verify password'}))

I do not know if the views.py file and the html file will help fix this error please state and I shall gladly update the question.


Solution

  • An EmailField [Django-doc] is not a widget. The standard widget for an EmailField is an EmailInput [Django-doc]:

    class UserAccount(forms.Form):
        # …
        email = forms.CharField(
            widget=forms.EmailInput(
                attrs={'class':'form-control', 'placeholder':'Email'}
            )
        )
        # …

    Note: Usually a Form or a ModelForm ends with a …Form suffix, to avoid collisions with the name of the model, and to make it clear that we are working with a form. Therefore it might be better to use UserAccountForm instead of UserAccount.