即使应该返回验证错误,Django 表单也不会返回? 更新

问题描述

在控制台中我可以看到它打印了“Less”字符串,这意味着控件进入了“if len(f_N)

####我的 forms.py 文件:####

from django import forms
from django.core.exceptions import ValidationError

class UserRegistrationForm(forms.Form):
    GENDER=[('male','MALE'),('female','FEMALE')]  
    firstName= forms.CharField()
    lastName= forms.CharField()
    email= forms.CharField(widget=forms.EmailInput,required=False,initial='Youremail@xmail.com')
    address=forms.CharField(widget=forms.Textarea)
    gender=forms.CharField(widget=forms.Select(choices=GENDER))
    password=forms.CharField(widget=forms.PasswordInput)
    ssn=forms.IntegerField()

    def clean_firstName(self):
        f_N=self.cleaned_data['firstName']
        print(f_N)
        if len(f_N)>15:
            raise forms.ValidationError('Max length allowed is 15 characters')
        if len(f_N) < 2:
            print(len(f_N))
            print("less")
            raise forms.ValidationError('Min length showuld be 2 characters')

        else:
            print("end")
            return f_N

#######我的 html 文件######

<!DOCTYPE html>
<html lang="en">

<head>
  <Meta charset="UTF-8">
  <title>User Registration</title>
</head>

<body>
  <h1> User Registration</h1>

  <table>
  <form method="post">
    
    {% csrf_token %}

    {{form.as_table}}
    </table>
    <button type="submit" name="button">Submit</button>
  </form>


</body>

</html>

##########My views.py 文件##########

from django.shortcuts import render
from .forms import UserRegistrationForm
from .models import User
# Create your views here.
def UserRegistrationView(request):
    form=UserRegistrationForm()
    if request.method=='POST':
        form_1=UserRegistrationForm(request.POST)
        if form_1.is_valid() :    
            #print(form_1.cleaned_data)
            form_1=form_1.cleaned_data 
            print(request.POST)
            print(form_1)
            user_1=User()
            user_1.firstName=form_1['firstName']
            user_1.lastName = form_1['lastName']
            user_1.email = form_1['email']
            user_1.save()
        
    return render(request,'formsDemo/userRegistration.html',{'form':form})

解决方法

参考这个话题https://docs.djangoproject.com/en/3.1/ref/forms/validation/#cleaning-a-specific-field-attribute

在您的 forms.py 中,您以正确的方式使用 ValidationError 导入了 from django.core.exceptions import ValidationError,但随后您在函数 clean_firstName() 中以错误的方式提升了它,应该是

    raise ValidationError('..')

而不是

    raise forms.ValidationError('..')

更新

在您的 views.py 中,既然您有 form_1=UserRegistrationForm(request.POST),那么您应该将 form_1 传递给 render 语句中的上下文,而不是 form。任何可以以正确方式做事的方式(并且您不再需要第二个 form_1):

def UserRegistrationView(request):

    form=UserRegistrationForm()

    if request.method=='POST':

        form=UserRegistrationForm(request.POST)

        if form.is_valid():
            user = form.save(commit=False)
            user.save()

            # Note: 
            # 1. if it happens 'form.is_valide()' returns false,then you'll
            # get the errors in 'form.errors' bag.
            # 2. you don't need to import User Model since you are using 'formMdel'

            # maybe you need to redirect to home page if you successfully saved
            # the new user .. display a flash message .. 

    return render(request,'formsDemo/userRegistration.html',{'form':form})

参考这个教程https://tutorial.djangogirls.org/en/django_forms/

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...