作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到了 ValidationError 问题。
from django import forms
class life_contract_data(forms.Form):
age = forms.CharField()
period = forms.CharField()
premium = forms.CharField()
percentage = forms.CharField()
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,
})
Added template.html
<form action="/life/life_contract/contract_output/" method="post">{% csrf_token %}
{% for field in form %}
<div class="float" id="form_fields">{{field}}{{field.label}}</div><br />
{% endfor %}
<input type="submit" value="Submit" />
</form>
实际上我希望如果用户输入年龄>=65且周期>5,他/她会遇到错误来纠正他/她的输入。但我看到来自 django 的错误消息:
[u'Age must be lower than 65']
问题出在哪里???
最佳答案
您遇到的问题是您在 View 中进行验证,而不是让表单在表单的 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
您的 View 还需要更改为名为 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
关于python - 如何在本例中激活 ValidationError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36460126/
我是一名优秀的程序员,十分优秀!