首页 > 解决方案 > 在 django 中自定义 LoginView 时可以获得cleaned_data

问题描述

Django 3.2 初学者。我正在尝试在我的登录屏幕上添加来自 Google 的 Recaptcha V3。

问题是表单未经验证“ '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)是问题,但我不知道该怎么做。

非常感谢你的帮助,

- - 编辑 - -

  1. 正如您在调试器中看到的那样,用户名/密码是字符串...不知道为什么 pycharm 将其转换为数组。https://ibb.co/nPVdzNp

  2. 添加后同样的问题


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)

标签: pythondjangoauthenticationcaptcha

解决方案


这里有两个时刻:

  1. username并且password表单数据中的字段是数组,这是错误的 - 您需要检查如何向 Django 发出 POST 请求并发送字符串,而不是数组。

  2. 由于用户名/密码字段是数组(不是字符串) -form.is_valid返回False,并且如果表单无效,则不会有任何 cleaned_data属性,因为它仅在表单有效并且实际上有一些有效数据时才会出现。


推荐阅读