简体   繁体   中英

Django forms difference, one works, the second one doesn't

I've got a kind strange problem. I've got two different (but almost the same forms and validation). The validation in first one works, in the second one doesn't. Can someone tell me why?

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

View:

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})

And the html template:

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

The validation should be like that clean_<fieldname> . ( Docs )

In your case the function is clean_<fieldname>_value .

so change the name of your function to just clean_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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