У объекта 'AuthenticationForm' нет атрибута 'cleaned_data'
Я переопределяю пользовательский логин django, импортируя AuthenticationForm и используя приведенный ниже код в моем views.py, но единственная проблема, которую я получаю, заключается в том, что когда я пытаюсь очистить форму, она всегда выдает ошибку: У объекта 'AuthenticationForm' нет атрибута 'cleaned_data'. Что я должен сделать, чтобы решить эту проблему? Вот мой views.py для переопределения пользовательского логина django
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})
вместо этого:
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 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)
Надеюсь, вы сможете это понять
Вы не можете использовать .cleand_data['something']
перед вызовом .is_valid
метода формы.
Решение:
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.