Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoengine ReferenceField mongoengine.errors.ValidationError

Need your help. I try to work with mongoengine, flask, flask-login.

My model:

class Post(db.Document):
   text = db.StringField(max_length=240)
   pub_date = db.DateTimeField(default=datetime.datetime.now)
   author = db.ReferenceField(Member)

And I get current user (flask-login):

from flask.ext.login import current_user

Than in views.py:

new_post = Post()
    new_post.text = 'bla-bla'
    #new_post.author = current_user                                 #- DON`T WORK
    new_post.author = Member.objects.get(id=current_user.id)        #-WORK (WHY?)
    new_post.save()

What wrong in new_post.author = current_user if new_post.author = Member.objects.get(id=current_user.id) - work okay.

If try with new_post.author = current_user - get error:

mongoengine.errors.ValidationError
ValidationError: ValidationError (Post:None) (A ReferenceField only accepts DBRef or documents: ['author'])

Thx, people.

like image 475
lov3catch Avatar asked Dec 26 '22 14:12

lov3catch


1 Answers

These errors happen because current_user has the LocalProxy type, while mongo is looking for a reference. While current_user in many ways works the same way as the actual Member object it proxies for, it can't be used as a reference because there is no information about the reference collection for mongo to use as a DBRef.

If you want to avoid Member.objects.get(id=current_user.id) to get the actual object, you can just get the get the actual Member object from current_user:

new_post.author = current_user._get_current_object()

or just the DBRef:

new_post.author = current_user.to_dbref()
like image 104
Max Avatar answered Dec 28 '22 05:12

Max