>>> u = users.User(id=None, username=' am...@webaroo.com', email='am...@webaroo.com')
>>> u.save()
>>> u2 = users.User(id=None, username='am...@webaroo.com ', email='am...@webaroo.com')
>>> u2.save()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/home/l2g/amitu/DownloadServer/django_src/django/utils/functional.py", line 3, in _curried
return args[0](*(args[1:]+moreargs), **dict(kwargs.items() + morekwargs.items()))
File "/home/l2g/amitu/DownloadServer/django_src/django/core/meta/__init__.py", line 1026, in method_save
','.join(placeholders)), db_values)
File "/home/l2g/amitu/DownloadServer/django_src/django/core/db/base.py", line 10, in execute
result = self.cursor.execute(sql, params)
File "/home/l2g/amitu/DownloadServer/django_src/django/core/db/backends/mysql.py", line 32, in execute
return self.cursor.execute(sql, params)
File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 137, in execute
self.errorhandler(self, exc, value)
File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.IntegrityError: (1062, "Duplicate entry 'am...@webaroo.com' for key 2")
>>>
from django.core.db import dbmod
try:
u2.save()
except dbmod.Database.IntegrityError:
//handle error
pass
Though, a better way in your case is improving the view code to check
existing user with the same username ahead of time, and rely less on
catching the database exception since not every database trigger the
same exception class on the same error.
Many thanks
David
As Dody Suria Wijaya suggested, you should improve your view code to
validate that the user isn't duplicate. Don't rely on the database to
check things; when using Django, database constraints are just a final
safety layer -- not a high-level source of validation.
Adrian
--
Adrian Holovaty
holovaty.com | djangoproject.com | chicagocrime.org
On 1/6/06, Amit Upadhyay <upad...@gmail.com> wrote:
> What is the rigth way of catching IntegrityError, the traceback I get
> suggests using _mysql_exceptions.IntegrityError, which is
> wrong because it assumes mysql, as well as it goes against the general
> python guideline of not using "hidden" members of modules.
As Dody Suria Wijaya suggested, you should improve your view code to
validate that the user isn't duplicate. Don't rely on the database to
check things; when using Django, database constraints are just a final
safety layer -- not a high-level source of validation.