Validation Errors -- which field is producing the error?

624 views
Skip to first unread message

Jorge Escobar

unread,
Apr 19, 2012, 9:56:02 PM4/19/12
to mongoeng...@googlegroups.com
Hi guys,

I am trying to see how to leverage the existing validation on mongoengine (I am on 0.6.5).

I have a URLField that I am passing a bad value. Sure enough I get an error:

> profile.homepage
u'htp:/loco.com'

> profile.save()
*** ValidationError: Errors encountered validating document

I've seen some posts in this group talking about an updated Validation class, but right now, is there a way to see which field produced the error when I do the save?

Thanks in advance!

Jorge Escobar

unread,
Apr 21, 2012, 8:25:14 PM4/21/12
to mongoeng...@googlegroups.com
Ok, I got it. In case anyone lands in here.

I have a profile object with a homepage field which is a URLField type.

Put the following on top of your python script:

from mongoengine.base import ValidationError

Then you can do an actual check before you save and you will get an errors dictionary on the ValidationError object:

try:
   profile.validate()
except ValidationError as e:
   if e.errors.get('homepage'):
      print "INVALID_URL"

The ValidationError.errors object looks like this (it will list all fields that have errors):

e.errors
{'homepage': ValidationError(Invalid URL: htp://loco.com ("homepage"),)}

Hope this helps someone out there...

Ross Lawley

unread,
Apr 25, 2012, 7:54:29 AM4/25/12
to mongoeng...@googlegroups.com
Thanks Jorge,

Apologies for not getting back to you with the answer, been too busy recently!

I've added a ticket to improve the docs: https://github.com/MongoEngine/mongoengine/issues/9

Regards,

Ross

Jorge Escobar

unread,
Apr 25, 2012, 10:22:15 AM4/25/12
to mongoeng...@googlegroups.com
No problems Ross! Glad I'm contributing a little bit... :)

On Wednesday, April 25, 2012 at 7:54 AM, Ross Lawley wrote:

Thanks Jorge,

Apologies for not getting back to you with the answer, been too busy recently!

I've added a ticket to improve the docs: https://github.com/MongoEngine/mongoengine/issues/9

Regards,

Ross
Reply all
Reply to author
Forward
0 new messages