我正在尝试允许用户通过包含try:...except ValueError:
来提交数据以捕获丢失的数据,但是即使包含所有输入值也会触发除外。
def sByInfo(request):
print "\n \n NEW CALL"
ranked = Ranked.objects.all()
unranked = Unranked.objects.all()
ranked_matches = [] # List for ranked institution matches
unranked_matches = [] # List for unranked institution matches
try:
gpa = request.GET['gpa']
gpa = float(gpa)
print gpa
pcat = request.GET['pcat']
pcat = int(pcat)
print pcat
try:
city = request.GET['city']
state = request.GET['state']
print "{}, {}".format(city, state)
position = getPos(city, state)
lati = Decimal(position['lat'])
loni = Decimal(position['lon'])
print "\n RANKED"
for x in ranked:
print x.name
average_gpa = (x.gpa_expected + x.gpa_overall) / 2
print average_gpa
if gpa >= average_gpa:
print "GPA good"
if ranked_matches.index(x):
print "School already added"
else:
ranked_matches.append(x)
print "School added"
else:
print "GPA too low"
if pcat >= x.min_pcat:
if ranked_matches.index(x):
print "School already added"
else:
ranked_matches.append(x)
else:
print "PCAT too low"
lat = Decimal(x.lat)
lon = Decimal(x.lon)
difference = posDifference(lati, loni, lat, lon)
print "Distance is {} miles".format(difference)
if difference <= 150:
if ranked_matches.index(x):
print "School already added"
else:
ranked_matches.append(x)
else:
print "School out of range"
print "\n UNRANKED"
for y in unranked:
print y.name
average_gpa = (y.gpa_expected + y.gpa_overall) / 2
if gpa >= average_gpa:
if unranked_matches.index(y):
print "School already added"
else:
unranked_matches.append(y)
else:
print "GPA too low"
if pcat >= y.min_pcat:
if unranked_matches.index(y):
print "School already added"
else:
unranked_matches.append(y)
else:
print "PCAT too low"
lat = Decimal(y.lat)
lon = Decimal(y.lon)
difference = posDifference(lati, loni, lat, lon)
print "Distance is {} miles".format(difference)
if difference <= 150:
if unranked_matches.index(y):
print "School already added"
else:
unranked_matches.append(y)
else:
print "School out of range"
except ValueError: ## City or State was not submitted
print "City or state missing"
try:
state = request.GET['state']
except ValueError:
print "City and state missing"
except ValueError:
return render('You must enter both GPA & PCAT scores')
return render_to_response('results.html', {'ranked_matches' : ranked_matches, 'unranked_matches' : unranked_matches}, context_instance = RequestContext(request))
第一个for
循环经过一次迭代而没有明显的失败,然后引发第一个嵌套异常,返回“City or state missing”消息。我很困惑为什么在提交所有值时都会引发此异常。
我认为问题必须出现在if
声明
if ranked_matches.index(x):
print "School already added"
else:
ranked_matches.append(x)
print "School added"
感谢所有帮助,谢谢。
答案 0 :(得分:1)
我不认为ValueError
足够强大,
如果数据数据类型不正确
int('test')
它会引发ValueError
,因此它不足以检查字段是否存在。
更强大的方法是使用djangos built in Forms。它允许您指定数据类型和必填字段,django将为您处理验证。