gpt4 book ai didi

python - 如何在本例中激活 ValidationError

转载 作者:行者123 更新时间:2023-11-30 22:57:47 24 4
gpt4 key购买 nike

我遇到了 ValidationError 问题。

forms.py
from django import forms

class life_contract_data(forms.Form):
age = forms.CharField()
period = forms.CharField()
premium = forms.CharField()
percentage = forms.CharField()

views.py
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

模板.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com