Home > Net >  'AuthenticationForm' object has no attribute 'cleaned_data'
'AuthenticationForm' object has no attribute 'cleaned_data'

Time:05-28

I override a custom django login by importing the AuthenticationForm and using the code below in my views.py but the only problem Im getting is that when i try to clean the form it always gives an error: 'AuthenticationForm' object has no attribute 'cleaned_data'. What should I do to resolve this problem? Here is my views.py for overriding custom django login

from django.contrib.auth.forms import AuthenticationForm 
def auth_login(request):
if request.user.is_authenticated:
    return redirect('/')

else:
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        username = request.POST['username']
        password = request.POST['password']

        username = form.cleaned_data['username']

        user = authenticate(username=username,password=password)

        if user:
            if user.is_superuser:
                login(request,user)
                return redirect('/dashboard')

            else:
                login(request,user)
                return redirect('/')

        else:
            messages.error(request,'Username or password not correct')
            return redirect('/accounts/login')
        

    return render(request,'registration/login.html',{'form':form})

CodePudding user response:

instead of this:

if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        username = request.POST['username']
        password = request.POST['password']

        username = form.cleaned_data['username']

        user = authenticate(username=username,password=password)

try this:

 if request.method == 'POST' and form.is_valid():
        form = AuthenticationForm(request.POST)
        username = request.POST['username']
        password = request.POST['password']

        username = form.cleaned_data['username']

        user = authenticate(username=username,password=password)

I hope you may get this

CodePudding user response:

You can't use .cleand_data['something'] before calling .is_valid method of form.

Solution:

def dummy_view(request):
    if request.method == 'POST':
        form = DummyForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            # Rest of the code.
  • Related