flask-mongoengine icon indicating copy to clipboard operation
flask-mongoengine copied to clipboard

Error with ListField(ReferenceField) and MongoEngine after updating with add_to_set__

Open fmatray opened this issue 8 years ago • 2 comments

A small issue when using flask-admin and mongoengine.

Example of error:

class User(UserMixin, db.Document):
  email = db.StringField(max_length=80)

class Team(db.Document):
  members=db.ListField(db.ListField(db.ReferenceField(User), default=[]))

def teaminvite(team_id=None):
    t=Team.objects.get(id=team_id)
    u=User(email=form.email.data).save()
    t.update(add_to_set__members=u)

Editing team with flask-admin works fine before the teaminvite. But once a user is added using add_to_set__members an error appeared in admin.

TypeError: getattr(): attribute name must be string
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask_mongoengine/wtf/fields.py", line 117, in _is_selected
return item in self.data
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mongoengine/base/document.py", line 240, in __contains__
val = getattr(self, name)

This is a correction (perhaps not the best) :

class QuerySetSelectMultipleField(QuerySetSelectField):
    def _is_selected(self, item):
      if not self.data:
          return False
    if self.data is list:
        return item in self.data
    else:
        return item in [self.data]

fmatray avatar Jun 17 '16 09:06 fmatray

Hi @fmatray! I'd love to see what self.data contains in QuerySetSelectMultipleField._is_selected and how it differs depending whether we save the Team doc with t.save() vs t.update(add_to_set__members=u).

The fact it differs is concerning, and I think we need to get to the bottom of this before hacking away a solution like the one you proposed. Thanks for suggesting it though!

wojcikstefan avatar Nov 27 '16 04:11 wojcikstefan

@fmatray, still interested in this? Or should we close this issue?

lafrech avatar Jan 22 '17 23:01 lafrech