在Django中自定义LoginView时可以获得清理的\u数据

2024-09-27 21:30:35 发布

您现在位置:Python中文网/ 问答频道 /正文

Django3.2的初学者。我正试图在我的登录屏幕上添加一个来自谷歌的Recaptcha V3

  • 我正在使用配置良好的django-recaptcha3
  • 徽标显示在我的登录页面上
  • 在调试json响应时,调用ReCaptchaField.clean是正常的

问题是表单没有经过验证 ““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)出了问题,但我不知道该怎么办

非常感谢你的帮助

---编辑--

  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)

Tags: djangonamefromimportformdataisrequest
2条回答

这里有两个时刻:

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

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

问题出在django-recaptcha3包中

  1. 验证发生在post方法之后,我可以使用表单\u valid

def form_valid(self, form):
    if form.is_valid():
        captcha_score = form.cleaned_data['captcha']
        print("SCORE " + str(captcha_score))
    return super().form_valid(form)

  1. 雪企鹅\django\recaptcha3\fields.py中,我更改了 返回值[0]返回json_响应['score']中的第63行

谢谢你的帮助

相关问题 更多 >

    热门问题