繁体   English   中英

Django forms 的区别,一个有效,第二个无效

[英]Django forms difference, one works, the second one doesn't

我有一个奇怪的问题。 我有两个不同的(但几乎相同的 forms 和验证)。 第一个验证有效,第二个验证无效。 有人能告诉我为什么吗?

1)

class SignUpForm1(forms.Form):
test_value = forms.CharField(
    label='Your name',
    max_length=100,
    widget=forms.TextInput(attrs={'class': "input"})
)

def clean_test_value(self):
    data = self.cleaned_data.get('test_value')
    print(data)
    if data != "abc":
        raise forms.ValidationError("Error")
    return data
class SignUpForm2(forms.Form):
name = forms.CharField(
    label='name',
    max_length=100,
    widget=forms.TextInput(attrs={'class': "input"})
)

def clean_name_value(self):
    data = self.cleaned_data.get('name')
    print(data)
    if data != "abc":
        raise forms.ValidationError("Error")
    return data

看法:

class SignUpView(View):
def get(self, request):
    form = SignUpForm1() #or SignUpForm2()
    return render(request, "index.html", {'form': form})
def post(self, request):
    form = SignUpForm1(request.POST) #or SignUpForm2(request.POST)
    if form.is_valid():
        print('valid')
    return render(request, "index.html", {"form": form})

以及 html 模板:

enter code here<form action="" method="post" class="formField">
{% csrf_token %}
{{form}}
<button type="submit" class="btn-form">Test</button>

验证应该是这样clean_<fieldname> 文档

在您的情况下, function 是clean_<fieldname>_value

所以将您的 function 的名称更改为clean_name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM