【发布时间】:2021-05-12 12:42:49
【问题描述】:
我创建了一个视图,用户可以在其中注册使用带有验证功能的表单。 但是,这些功能不起作用。
class SignUpPage(View):
def get(self, request):
form = SignUpForm()
return render(request, "signup.html", {'form': form})
def post(self, request):
form = SignUpForm(request.POST or None)
if form.is_valid():
redirect('/signup')
else:
form = SignUpForm()
ctx = {"form": form}
return render(request, "signup.html", ctx)
形式:
class SignUpForm(forms.Form):
first_name = forms.CharField(max_length=32, required=True)
last_name = forms.CharField(max_length=32, required=True)
username = forms.CharField(max_length=32, required=True)
email = forms.CharField(label="email")
password1 = forms.CharField(label="Password", max_length=32, widget=forms.PasswordInput(attrs={'class': 'password'}))
password2 = forms.CharField(label="Password Again", max_length=32, widget=forms.PasswordInput(attrs={'class': 'password'}))
date_of_birth = forms.DateField(label="Date of birth", required=True, widget=forms.SelectDateWidget(years=YEARS, attrs={'class': 'date-select'}))
def validate_email(self):
data = self.cleaned_data.get('email')
if User.objects.filter(email=data).exists():
raise forms.ValidationError("This email is already registered")
return data
def validate_age(self):
user_date = str(self.cleaned_data['date_of_birth'])
year = int(user_date[0:4])
month = int(user_date[5:7])
day = int(user_date[8:10])
today = dt.today()
if int(today.year) - year < 18:
raise forms.ValidationError("You must be 18 years old to have an account")
elif int(today.year) - year == 18 and int(today.month) - month < 0:
raise forms.ValidationError("You must be 18 years old to have an account")
elif int(today.year) - year == 18 and int(today.month) - month == 0 and int(today.day) - day < 0:
raise forms.ValidationError("You must be 18 years old to have an account")
else:
return user_date
谁能解释一下为什么这些验证功能不起作用? 我什至尝试过:
def validate_email(self):
data = self.cleaned_data.get('email')
if data == "abc":
raise forms.ValidationError("This email is already registered")
return data
通过在输入字段中写入“abc”。
或:
data = self.cleaned_data['email']
更多细节的HTML代码:
<form action="" method="post" class="formField">
{% csrf_token %}
{{form}}
<div class="s-password">
<input type="checkbox" class="form-checkbox" id="show-password" onclick="showPassword()">
<label for id="s-password">Show Password</label>
</div>
<div class="form-btn-wrapper">
<button type="submit" class="btn-form">Sign Up</button>
<input type="checkbox" class="form-checkbox" id="check" name="remember">
<label for id="remember">Remember me</label>
</div>
<footer class="form-footer">
<p>Already have an account <a href="/login">Login now</a></p>
</footer>
</form>
【问题讨论】: