Django3.2的初学者。我正试图在我的登录屏幕上添加一个来自谷歌的Recaptcha V3
问题是表单没有经过验证 ““CustomAuthenticationForm”对象没有属性“cleaned_data””
执行此操作时发生错误
form.is_valid() # FALSE !!
captcha_score = form.cleaned_data['captcha'].get('score')
print("SCORE" + str(captcha_score))
这是我的密码:
在url.py中
from django.urls import path
from .views import CustomLoginView
urlpatterns = [
path('login', CustomLoginView.as_view(), name='login'),
]
格式为.py
from django.contrib.auth.forms import AuthenticationForm
from snowpenguin.django.recaptcha3.fields import ReCaptchaField
class CustomAuthenticationForm(AuthenticationForm):
captcha = ReCaptchaField()
在视图中.py
from django.contrib.auth.views import LoginView
from django.views import generic
from django.contrib.auth.forms import AuthenticationForm
from .forms import CustomAuthenticationForm
class CustomLoginView(LoginView):
def post(self, request, *args, **kwargs):
if request.method == "POST":
form = CustomAuthenticationForm(request.POST)
if form.is_valid():
captcha_score = form.cleaned_data['captcha'].get('score')
print("SCORE" + str(captcha_score))
return super().post(self, request, *args, **kwargs)
form_class = CustomAuthenticationForm
template_name = 'accounts/login.html'
请求。发布
<QueryDict: {'csrfmiddlewaretoken': ['TGoQaJTZACp4MbwB3iGVVdL4IHbqWDQaIhE1ldb9M8fkpjSRDHV7l1A1tTb62f3B'], 'g-recaptcha-response': ['03AGdBq270w7Z23MTavtAHLAUNSY9IWKuVpFZe0eueIiXimW6BvhTeWKANQQIFj43m903GA-cUA-dXZm7I6br.......5Z9vdM6RY9v-Kk1ZLX1uwH5nSoc7ksWUQuA00w0T8'], 'username': ['remi@XXXXXe.fr'], 'password': ['vXXXXX']}>
这是正常的。form.is\u valid()失败,我怀疑是form=CustomAuthenticationForm(request.POST)出了问题,但我不知道该怎么办
非常感谢你的帮助
---编辑--
class CustomAuthenticationForm(AuthenticationForm):
captcha = ReCaptchaField()
class Meta(AuthenticationForm):
model = CustomUser
及删除
class CustomUser(AbstractUser):
# first_name = models.CharField(max_length=150)
# last_name = models.CharField(max_length=150)
这里有两个时刻:
表单数据中的
username
和password
字段是数组,这是错误的-您需要检查如何向Django发出POST请求并发送字符串,而不是数组由于username/pass字段是数组(不是字符串)-
form.is_valid
返回False
,并且如果表单无效,则会有无cleaned_data
属性,因为它仅在表单有效且实际具有一些有效数据时才出现问题出在django-recaptcha3包中
谢谢你的帮助
相关问题 更多 >
编程相关推荐