【问题标题】:django form is valid() failsdjango 表单有效()失败
【发布时间】:2017-02-19 12:05:21
【问题描述】:

我正在尝试使用 django 创建一个注册表单,当我提交我的表单时,is valid() 函数失败,我不知道为什么。我的注册和登录页面都在一个 html 页面上,不过,我已将所有字段名称称为不同的名称,例如 login_username。

forms.py

class SignUpForm(forms.Form):
    username = forms.CharField(label='Username', max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Username'}))
    conUsername = forms.CharField(label='Confirm Username', max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Confirm Username'}))
    firstName = forms.CharField(label='First Name', max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Firstname'}))
    lastName = forms.CharField(label='Last Name', max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter LastName'}))
    email = forms.CharField(label='Email', max_length=220,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Email','type':'email'}))
    conEmail = forms.CharField(label='Confirm Email', max_length=220,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Confirm Email','type':'email'}))
    password = forms.CharField(label="Confirm Password", max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','type':'password','placeholder':'Enter Password'}))
    conPassword = forms.CharField(label="Confirm Password", max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','type':'password','placeholder':'Confirm Password'}))

views.py

def SignUp(request):
    regForm = SignUpForm()
    form = LoginForm()
    if request.method == 'POST':

        if regForm.is_valid():
            username = regForm.cleaned_data('username')
            print username
            confirm_username = regForm.cleaned_data('conUsername')
            first_name = regForm.cleaned_data('firstName')
            last_name = regForm.cleaned_data('lastName')
            email = regForm.cleaned_data('email')
            confirm_email = regForm.cleaned_data('conEmail')
            password = regForm.cleaned_data('password')
            confirm_password = regForm.cleaned_data('conPassword')



                #try:
                    #user = User.objects.get(username=request.POST['username'])
                    #return render(request, 'index.html',{'error_message':'username must be unique'})
                #except User.DoesNotExist:  
                    #user = User.objects.create_user(request.POST['username'], password=request.POST['password'])
                    #login(request, user)
                    #return render(request, 'index.html')
        else: 
            return render(request,'index.html',{'username_error':'usernames didnt match','form':form,'regForm':regForm})


    else:
        return render(request, 'index.html',{'form':form,'regForm':regForm})

index.html

<form class="regForm" method="POST" action="{% url 'signup' %}">
        {% csrf_token %}
        {{username_error }}
        <div class="row">
        <div class="col-md-2 col-md-offset-8">
        <div class="form-group">
            {{regForm.error_message.username}}
           {{ regForm.username }}
        </div>
    </div>
      <div class="col-md-2 ">
    <div class="form-group">
      {{error_message.conUsername}}
           {{ regForm.conUsername }}
        </div>
    </div>
</div>
      <div class="row">
        <div class="col-md-2 col-md-offset-8">
        <div class="form-group">
           {{ regForm.firstName }}
        </div>
    </div>
        <div class="col-md-2">
    <div class="form-group">
           {{ regForm.lastName }}
        </div>
    </div>
</div>
        <div class="row">
        <div class="col-md-4 col-md-offset-8">
        <div class="form-group">
           {{ regForm.email }}
        </div>
    </div>
</div>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
        <div class="form-group">
           {{ regForm.conEmail }}
        </div>
    </div>
</div>
<div class="row">
        <div class="col-md-2 col-md-offset-8">
        <div class="form-group">
           {{ regForm.password }}
        </div>
    </div>
      <div class="col-md-2">
    <div class="form-group">
           {{ regForm.conPassword }}
        </div>
    </div>
</div>

      <div class="row">
        <div class="col-md-3 col-md-offset-9">
        <div class="form-group">
            <button type="submit" id="regBtn" class="btn btn-default">Submit</button>
        </div>
    </div>
</div>

      </form>

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    现在您的表单始终为空,因此无效。您忘记将请求 POST 内容添加到表单中。

    def SignUp(request):
        # ...
        if request.method == 'POST':
            regForm = SignupForm(request.POST)  # form needs content
            if regForm.is_valid():
                # ...
    

    如果您在拨打.is_valid() 时遇到问题,您可以print(regForm.errors) 看看发生了什么。

    【讨论】:

      【解决方案2】:

      你有两个主要问题。首先,您永远不会将 POST 数据传递给表单,因此它永远不会有效。

      其次,由于某种原因,您忽略了表单可以告诉您的有关其无效原因的所有信息,并且总是返回“用户名不匹配”。更重要的是,您甚至没有做任何事情来比较用户名,因此错误消息永远不会准确。

      您应该按照文档中描述的模式修改视图:

      def SignUp(request):
          if request.method == 'POST':
              regForm = SignUpForm(request.POST)
              if regForm.is_valid():
                   ...
                   return redirect(somewhere)
          else:
              regForm = SignUpForm()
          return render(request, 'index.html', {'regForm':regForm})
      

      并确保在您的模板中包含 {{ form.errors }} 以显示验证失败的原因。

      【讨论】:

      • 我添加了 username_error 消息,以便将某些内容输出到屏幕上,以便我可以检查 form.is_valid 函数是否正常工作
      猜你喜欢
      • 2012-06-19
      • 2018-01-04
      • 2011-05-31
      • 2010-10-29
      • 2014-04-18
      • 2017-06-25
      • 2017-01-25
      • 2020-03-12
      • 1970-01-01
      相关资源
      最近更新 更多