Search code examples
pythonpython-3.xdjangodjango-forms

Django accounts custom AuthenticationForm failing as invalid


Why is this giving form invalid? My username password input is correct.

forms.py

class CustomAuthForm(AuthenticationForm):
    username = forms.CharField(required=True, max_length = 50,
 widget=forms.EmailInput(attrs={"placeholder": "Email", "class":"form-control"}))

    password = forms.CharField(required=True, max_length = 50,
 widget=forms.PasswordInput(attrs={"placeholder":"Password", "class":"form-control"}))

   

views.py

@csrf_protect
def user_login(request):
    if request.user.is_authenticated:
        return redirect('/')

    form=CustomAuthForm(request.POST or None)
    print(request.POST)
    if form.is_valid():
        print(form.cleaned_data)
    else:
        print ('form invalid')

Console print

<QueryDict: {'csrfmiddlewaretoken': ['mt5a3e9KyCbVg4OokaDeCu97EDrHVInAwVJmmK3a2xn0Nn4KRi0gt7axWJyRDMmT'], 
'username': ['[email protected]'], 'password': ['mypass']}>

form invalid

Solution

  • Looking at the source code for the AuthenticationForm that your CustomAuthForm is based on, one can see that its __init__ function is a little different than most of the other forms. In particular, it takes a request object as its first parameter.

    # https://github.com/django/django/blob/main/django/contrib/auth/forms.py
    
    def __init__(self, request=None, *args, **kwargs):
        """
        The 'request' parameter is set for custom auth use by subclasses.
        The form data comes in via the standard 'data' kwarg.
        """
        self.request = request
        self.user_cache = None
        super().__init__(*args, **kwargs)
    

    Therefore, change the syntax in your view:

    # from
    form=CustomAuthForm(request.POST or None)
    
    # to
    form=CustomAuthForm(None, request.POST)