I'm trying to figure out the problem in this short paragraph of code. Any help would be appreciated. Regardless of what I specify User.email to be, it always returns 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'}
I have confirmed that the false being returned is coming from except NameError.
Also, isAddressValid() is just 开发者_开发问答a method to check the structure of an e-mail address.
Thanks.
You haven't included a return
statement for the positive case... Also, when a function doesn't include a return
statement, the caller receives None
instead...
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
Actually you have two values.
0
None
If you print the value instead of using it in an if-statement, you'll see the two conditions. Consider adding print statements to see what the value actually is.
if (isAddressValid(self.email) == 0):
If this is True, you get 0
.
If this is False, you'll get None
.
And the exception give 0
.
If I were re-writing this code, I would go for something like this:
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
Im not sure what problem you are talking about , but you are always returning 0
Try adding an else clause for the case of the Valid Email (which you are currently not considering)
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
You said isAddressValid
is a method, right? Since add
is also a method, perhaps you have to prepend a self.
:
if (self.isAddressValid(self.email) == 0):
This most probably will deal with your NameError
.
After that, add an else
clause when the check succeeds:
…
self.errors['email'] = 'You have entered an invalid e-mail address'
return 0
else:
return 1
精彩评论