我遇到ValidationError问题。
UIImage(named: _)
from django import forms
class life_contract_data(forms.Form):
age = forms.CharField()
period = forms.CharField()
premium = forms.CharField()
percentage = forms.CharField()
添加了template.html
from django.shortcuts import render
from .forms import *
from django import forms
def contract_output(request):
form = life_contract_data(request.POST)
age = range(int(request.POST['age']),int(request.POST['age'])+int(request.POST['period']))
period = range(1,int(request.POST['period'])+1)
premium_period = range(1, int(request.POST['period']))
premium = (request.POST['premium'])
percentage = int(request.POST['percentage'])
premium1 = []
premium_total_year = []
premium1.append(int(premium))
premium_total_year.append(int(premium1[0])*12)
for pre in premium_period:
premium1.append((premium1[pre-1]*percentage)/100 + premium1[pre-1])
premium_total_year.append(int(premium1[pre])*12 + int(premium_total_year[pre-1]))
if int(request.POST['age']) >= 65:
death_capital = 50000000
else:
death_capital = 100000000
if int(request.POST['age']) >= 65 and int(request.POST['period']) > 5:
raise forms.ValidationError("Age must be lower than 65") #THE CRAZY PROBLEM
return render(request, 'life/contract_output.html', {
'form':form,
'age':age,
'period':period,
'premium':premium1,
'percentage':percentage,
'death_capital':death_capital,
'premium_total_year':premium_total_year,
})
实际上我想如果用户输入年龄> gt = = 65且期间> 5,他/她将面临错误以纠正他/她的输入。但是我从django看到了这条错误消息:
[u'Age必须低于65']
问题出在哪里???
答案 0 :(得分:3)
您遇到的问题是您正在视图中进行验证,而不是让表单在表单的clean
方法中处理它
class life_contract_data(forms.Form):
age = forms.CharField()
period = forms.IntegerField()
premium = forms.CharField()
percentage = forms.CharField()
def clean(self):
cleaned_data = super(life_contract_data, self).clean()
if cleaned_data.get('age') >= 65 and cleaned_data.get('period') > 5:
raise forms.ValidationError("Age must be lower than 65")
return cleaned_data
您的观点也需要更改为调用is_valid
而不是
def contract_output(request):
form = life_contract_data(request.POST)
if not form.is_valid():
return render(request, 'life/contract_output.html', { 'form':form })
# Do something if it is valid
<form action="/life/life_contract/contract_output/" method="post">
{% csrf_token %}
{{ form }}
</form>
有关详细信息,请参阅Cleaning and validating fields that depend on each other