Simplest way to handle and display errors in a Python Pylons controller without a helper class
- by ensnare
I have a class User() that throw exceptions when attributes are incorrectly set. I am currently passing the exceptions from the models through the controller to the templates by essentially catching exceptions two times for each variable.
Is this a correct way of doing it? Is there a better (but still simple) way? I prefer not to use any third party error or form handlers due to the extensive database queries we already have in place in our classes.
Furthermore, how can I "stop" the chain of processing in the class if one of the values is invalid? Is there like a "break" syntax or something?
Thanks.
>>> u = User()
>>> u.name = 'Jason Mendez'
>>> u.password = '1234'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "topic/model/user.py", line 79, in password
return self._password
ValueError: Your password must be greater than 6 characters
In my controller "register," I have:
class RegisterController(BaseController):
def index(self):
if request.POST:
c.errors = {}
u = User()
try:
u.name = c.name = request.POST['name']
except ValueError, error:
c.errors['name'] = error
try:
u.email = c.email = request.POST['email']
except ValueError, error:
c.errors['email'] = error
try:
u.password = c.password = request.POST['password']
except ValueError, error:
c.errors['password'] = error
try:
u.commit()
except ValueError, error:
pass
return render('/register.mako')