django form.is_valid 返回 false

Posted

技术标签:

【中文标题】django form.is_valid 返回 false【英文标题】:django form.is_valid returns false 【发布时间】:2020-04-06 01:51:05 【问题描述】:

每当我提交表单并检查表单没有被提交并被重定向时。验证总是错误的。我输入了所有文件,它仍然显示相同。为什么一直这样显示?有什么不对?以下是我使用视图、模板和表单的文件。

views.py

def signincheck(request):

    if request.method == "POST":
        formsignin = FormSignup(request.POST,request.FILES)
        if formsignin.is_valid():
            return HttpResponse("Password not match 3")
            TbluserVar=Tbluser()
            TbluserVar.firstname=formsignin.cleaned_data['firstname']
            TbluserVar.lastname=formsignin.cleaned_data['lastname']
            TbluserVar.username=formsignin.cleaned_data['username']
            Password=formsignin.cleaned_data['password']
            ConfirmPassword=formsignin.cleaned_data['confirm_password']
            TbluserVar.mobilenumber=formsignin.cleaned_data['mobilenumber']
            Tbluser.dateofbirth=formsignin.cleaned_data['dob']
            Tbluser.dateofjoining=datetime.datetime.today()
            Tbluser.userlevel=0
            if Password != ConfirmPassword:
                messages.error(request,'Password and Confirm Password does not match')
                return redirect('/')

            else:
                try:
                    user = Tbluser.objects.get(username=formsignin.cleaned_data['username'])
                    messages.error(request,'Username not available. Try another one.')
                    return redirect('/')

                except:
                    PasswordEnc=hashlib.md5(Password.encode())
                    RealPassword=PasswordEnc.hexdigest()
                    TbluserVar.passwordenc=RealPassword
                    TbluserVar.save()
                    request.session['username']=TbluserVar.username
                    request.session['getFirstandLastName']=TbluserVar.firstname + " " + TbluserVar.lastname
                    FullName=request.session['getFirstandLastName']
                    return redirect('/index')

        else:
            return redirect('/')
    else:
        return HttpResponse("NOT CORRECT")

forms.py

class FormSignup(forms.Form):
    firstname=forms.CharField(
        max_length=30,
        widget=forms.TextInput(attrs='placeholder': 'First Name...','class':'loginform'))

    lastname=forms.CharField(
        max_length=30,
        widget=forms.TextInput(attrs='placeholder': 'Last Name...','class':'loginform'))

    username=forms.CharField(max_length=30,widget=forms.TextInput(attrs='placeholder': 'User Name...','class':'loginform'))
    password=forms.CharField(max_length=30,widget=forms.PasswordInput(attrs='placeholder': 'Password...','class':'loginform'))
    confirm_password=forms.CharField(max_length=30,widget=forms.PasswordInput(attrs='placeholder': 'Confirm Password...','class':'loginform'))
    mobilenumber=forms.CharField(max_length=30,widget=forms.TextInput(attrs='placeholder': 'Mobile Number...','class':'loginform'))
    dob=date = forms.DateTimeField(
        input_formats=['%d/%m/%Y'],
        widget=forms.TextInput(attrs=
        
            'class':'datepicker',
            'placeholder': 'Date of Birth...'

        ))

template.html

<div class="modal fade" id="modalSignUpForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header text-center">
                <h4 class="modal-title w-100 font-weight-bold">Sign in</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <form id="idlognform" method="POST" action="% url 'signupcheck' %" enctype="multipart/form-data">
                % csrf_token %
                <div class="modal-body mx-3">
                  <div class="md-form mb-4">
                    <i class="fas fa-lock prefix grey-text"></i>
                    FormSignup1.firstname
                  </div>

                  <div class="md-form mb-4">
                    <i class="fas fa-lock prefix grey-text"></i>
                    FormSignup1.lastname
                  </div>

                  <div class="md-form mb-4">
                    <i class="fas fa-lock prefix grey-text"></i>
                    FormSignup1.username
                  </div>

                  <div class="md-form mb-4">
                    <i class="fas fa-lock prefix grey-text"></i>
                    FormSignup1.password
                  </div>

                  <div class="md-form mb-4">
                    <i class="fas fa-lock prefix grey-text"></i>
                    FormSignup1.confirm_password
                  </div>

                  <div class="md-form mb-4">
                    <i class="fas fa-lock prefix grey-text"></i>
                    FormSignup1.mobilenumber
                  </div>

                  <div class="md-form mb-4">
                    <i class="fas fa-lock prefix grey-text"></i>
                    FormSignup1.dob
                  </div>
                  <div class="modal-footer d-flex justify-content-center">
                      <input class="btn btn-default" type="submit" id="signinbutton" value="Login">
                    </div>
                </div>
                form.errors
              </form>


            </div>
          </div>
        </div>

【问题讨论】:

您不应通过重定向来处理无效表单。您应该只在同一个模板中重新渲染绑定的表单,显示错误。看the example。在您的模板中,确保您还在每个字段下方显示错误(例如 FormSignup1.confirm_password.errors),或者在顶部仅显示 form.errors 以列出所有错误。 此外,您应该在表单中处理验证,而不是在视图中,因此您可以通过引发ValidationError 将错误添加到表单错误中。再次查看documentation。最后,不要像现在这样保存密码,这完全不安全。 Django 为您提供了安全的密码散列机制。 【参考方案1】:

这是因为您在 forms.py 中使用了dob=date=。它看起来不像一个有效的 django 表单。希望这会有所帮助。

【讨论】:

谢谢,它有帮助。不过这是我的失误。【参考方案2】:

稍后我会尝试您的代码。无论如何,只是阅读你可以试试这个: 在views.py中放入if formsignin.is_valid()的else:

formsignin = FormSignup()

但也许上述行为不是你想要的。 尤其是在 form.py 中:

def __init__(self, *args, **kwargs):
    super(FormSignup, self).__init__(*args, **kwargs)

【讨论】:

以上是关于django form.is_valid 返回 false的主要内容,如果未能解决你的问题,请参考以下文章

Django 表单不运行 form.is_valid

Django 消费者(Django 频道)中的表单数据验证(相当于 form.is_valid)

Django:form.is_valid 检查后,cleaned_data 缺少图像字段

Django form.is_valid() 总是假的

Django form.is_valid() 失败的基于类的视图 - Form、SingleObject、DetailMixins

使用ModelForm时,form.is_valid()返回False