我正在一个类中执行所有表单验证,并且希望能够将错误从类中获取到呈现的 html。我正在考虑的一种方法是创建一个全局变量“c”来存储所有错误并在类中设置它们,因为我仍然希望各个方法在失败时返回 false。这是一些示例代码:
class User():
def add(self):
#Check that e-mail has been completed
try:
#Validate e-mail address
if (isAddressValid(self.email)):
c.error = 'Invalid e-mail address'
return 0
except NameError:
c.error = 'No e-mail address specified'
return 0
是否有更好或首选的方法来做到这一点?
谢谢。
最佳答案
我喜欢使用字典来保存错误和警告。然后我可以在表单顶部或内联显示所有错误。我还定义了 error
和 warning
变量,以便我可以轻松区分两者。
class User(object):
def __init__(self):
self.messages = {}
def add(self):
error = False
warning = False
#Check that name has a space
try:
if (self.name.find(' ') == -1):
warning = True
self.messages['email'] = {'type': 'warning',
'msg': 'Your name has no space.'}
except NameError:
error = True
self.messages['email'] = {'type': 'error',
'msg': 'You have no name.'}
#Check that e-mail has been completed
try:
#Validate e-mail address
if (isAddressValid(self.email)):
error = True
self.messages['email'] = {'type': 'error',
'msg': 'Invalid e-mail address'}
except NameError:
error = True
self.messages['email'] = {'type': 'error',
'msg': 'No e-mail address specified'}
return error, warning
关于python - 在 python 中将错误从类传递到渲染的 html 的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2352201/