python - 在 django 中自定义 LoginView 时可以获得cleaned_data
问题描述
Django 3.2 初学者。我正在尝试在我的登录屏幕上添加来自 Google 的 Recaptcha V3。
- 我正在使用配置良好的 django-recaptcha3
- 徽标显示在我的登录页面上
- 在调用 ReCaptchaField.clean 时调试 json 响应是可以的!
问题是表单未经验证“ 'CustomAuthenticationForm'对象没有属性'cleaned_data' ”
当我这样做时发生错误
form.is_valid() # FALSE !!
captcha_score = form.cleaned_data['captcha'].get('score')
print("SCORE" + str(captcha_score))
这是我的代码:
在 urls.py
from django.urls import path
from .views import CustomLoginView
urlpatterns = [
path('login', CustomLoginView.as_view(), name='login'),
]
在 Forms.py 中
from django.contrib.auth.forms import AuthenticationForm
from snowpenguin.django.recaptcha3.fields import ReCaptchaField
class CustomAuthenticationForm(AuthenticationForm):
captcha = ReCaptchaField()
在 Views.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'
request.POST 给出
<QueryDict: {'csrfmiddlewaretoken': ['TGoQaJTZACp4MbwB3iGVVdL4IHbqWDQaIhE1ldb9M8fkpjSRDHV7l1A1tTb62f3B'], 'g-recaptcha-response': ['03AGdBq270w7Z23MTavtAHLAUNSY9IWKuVpFZe0eueIiXimW6BvhTeWKANQQIFj43m903GA-cUA-dXZm7I6br.......5Z9vdM6RY9v-Kk1ZLX1uwH5nSoc7ksWUQuA00w0T8'], 'username': ['remi@ XXXXe.fr'], '密码': ['vXXXXX']}>
这是正常的。form.is_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 请求并发送字符串,而不是数组。由于用户名/密码字段是数组(不是字符串) -
form.is_valid
返回False
,并且如果表单无效,则不会有任何cleaned_data
属性,因为它仅在表单有效并且实际上有一些有效数据时才会出现。
推荐阅读
- wordpress - Woocommerce 3.3 中的发布缩略图选项
- mysql - 根据连接表中的一种关系获取结果
- sql-server - 限制 SQL 存储过程参数中的位数
- asp.net-mvc - 如何将值从表中的按钮传递到 MVC 中的另一个视图?
- c# - 如果在运行子窗体窗口时单击父窗体会冻结,直到关闭子窗体
- php - 如何通过php,swift将服务器上的图像显示到iOS设备
- 3d - 在运行时导入另一个纹理(使用 .glb 格式的三个.js)
- python - Python:如何以高效的方式搜索大数组?
- kubernetes - Kubernetes Helm:如何在 pod 定义中传递依赖服务的外部 IP?
- xaml - uwp NavigationView 控件标题栏