我试图在这段短代码中弄清楚问题。任何帮助,将不胜感激。无论我指定User.email是什么,它总是返回false。
def add(self):
#1 -- VALIDATE EMAIL ADDRESS
#Check that e-mail has been completed
try:
#Validate if e-mail address is in correct format
if (isAddressValid(self.email) == 0):
self.errors['email'] = 'You have entered an invalid e-mail address';
return 0
except NameError:
self.errors['email'] = 'Please enter your e-mail'
return 0
>>> u = User()
>>> u.email = 'test@example.com'
>>> u.add()
0
>>> print u.errors
{'email': 'Please enter your e-mail'}
我已经确认返回的错误来自NameError。
另外,isAddressValid()只是一种检查电子邮件地址结构的方法。
感谢。
答案 0 :(得分:5)
您尚未为正面案例添加return
语句...此外,当函数不包含return
语句时,调用方会收到None
而不是def add(self):
#1 -- VALIDATE EMAIL ADDRESS
#Check that e-mail has been completed
try:
#Validate if e-mail address is in correct format
if (isAddressValid(self.email) == 0):
self.errors['email'] = 'You have entered an invalid e-mail address';
return False
except NameError:
self.errors['email'] = 'Please enter your e-mail'
return False
return True
。 。
{{1}}
答案 1 :(得分:1)
实际上你有两个值。
0
None
如果您打印值而不是在if语句中使用它,您将看到两个条件。考虑添加print语句以查看实际值是什么。
if (isAddressValid(self.email) == 0):
如果这是True,则会得到0
。
如果这是假的,您将获得None
。
例外情况为0
。
答案 2 :(得分:1)
如果我重写这段代码,我会选择这样的东西:
def add(self):
try:
if not isAddressValid(self.email):
self.errors['email'] = 'You have entered an invalid e-mail address';
except NameError:
self.errors['email'] = 'Please enter your e-mail'
return 'email' not in self.errors
答案 3 :(得分:0)
我不确定你在说什么问题,但你总是回来0
尝试为有效电子邮件(您目前没有考虑)的情况添加else子句
def add(self):
#1 -- VALIDATE EMAIL ADDRESS
#Check that e-mail has been completed
try:
#Validate if e-mail address is in correct format
if (isAddressValid(self.email) == 0):
self.errors['email'] = 'You have entered an invalid e-mail address';
return 0
else
return 1
except NameError:
self.errors['email'] = 'Please enter your e-mail'
return 0
答案 4 :(得分:0)
你说isAddressValid
是一种方法,对吧?由于add
也是一种方法,因此您可能需要预先添加self.
:
if (self.isAddressValid(self.email) == 0):
这很可能会处理您的NameError
。
之后,在检查成功时添加else
子句:
…
self.errors['email'] = 'You have entered an invalid e-mail address'
return 0
else:
return 1