Skip to content

After replace, FileField.__str__() returns an inconsistent and misleading <GridFSProxy: None> #710

@BurkovBA

Description

@BurkovBA

I'm using Django1.7b4, Mongoengine v0.8.7 and Python2.7. The bug originates in the the following scenario:

I create a ProfileDocument to store my website user's data. It has an Avatar FileField (Avatar = FileField()) to store user's avatar. Upon registration of a new user, the Avatar FileField is successfully populated with a stock image from my static folder. When user wishes to change an avatar in edit_profile view, I replace the old contents of Avatar Field
just as documentation tells to: http://docs.mongoengine.org/en/latest/guide/gridfs.html#replacing-files and DON'T SAVE request.user.profile.avatar yet:

 request.user.profile.avatar.replace(new_avatar, content_type="image/png")
 print "new_avatar = %s ..." % request.user.profile.avatar

The print returns <GridFSProxy: None>, while GridFSProxy.__repr__() returns something like <GridFSProxy: 45955817385>, where 45955817385 is grid_id.

The problem is in __str__() implementation:

    def __str__(self):
        name = getattr(self.get(), 'filename', self.grid_id) if self.get() else '(no file)'
        return '<%s: %s>' % (self.__class__.__name__, name)

Strangely, after replace, request.user.profile.avatar has 'filename' attribute equal to None, so instead of self.grid_id GridFSProxy.filename is used in __str__().

I don't quite understand the magic, going on when GridFSProxy is getting its attrbiutes, and where that 'filename' comes from, so I won't suggest any fixes.

I just think this behavior is inconsistent. It can also be misleading, cause mongoengine user can expect that he doesn't need to call save() on Document after replacing FileField in it (and documentation doesn't tell you to call save() after replacing). So mongoengine user might replace, not save, then close the database connection and on the next run, he gets a None object in his FileField. He starts debugging and finds that right after replace the value of FileField is <GridFSProxy: None> (while in fact replace was successful and FileField contains a valid file, so his problem's not here, but in missing save() rather). Confused user starts tearing his hair out...

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions