3

I am having some problems getting images from the database and showing them in my webpage.

First of all, I am using mongoengine, so here goes (part of) my models.py:

class Picture(EmbeddedDocument):
    image = ImageField()

class Post(Document):
    ...
    comments = ListField(EmbeddedDocumentField('Comment'))
    user = ReferenceField('User', reverse_delete_rule='CASCADE')
    images = ListField(EmbeddedDocumentField('Picture'))

Here is the code in my view where I save the images:

picture = Picture()

with tempfile.TemporaryFile() as f:
    f.write(file.read())
    f.flush()
    f.seek(0)
    picture.image.put(f)

picture.save()

post.images.append(picture)

post.save()

So, in the HTML page I have the following:

<p>{{ post.images[0].image }}</p>
<img src="{{ post.images[0].image }}">

The first line outputs: <ImageGridFsProxy: None>. The second, obviously, doesn't output a valid image.

Here is what I get when I do db.post.find(...) in the mongo shell:

{ "_id" : ObjectId("56325c4e66b3f6bf8beb9e03"), ... "images" : [ { "image" : ObjectId("56325c4e66b3f6bf8beb9e04") } ] }

Can someone help me with this?

Thanks!

Larissa Leite
  • 1,358
  • 3
  • 21
  • 36
  • is post.images[0].image giving a valid url to an image? – Ryan Oct 28 '15 at 19:15
  • @Ryan if I print post.images[0].image in the view, it gives me this: ValidationError: u'' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string – Larissa Leite Oct 28 '15 at 19:29
  • print post.images[0].image.name Do you get a path back? If you get just the name (ex: test.jpg), try combining with the path to your temporary files. – Ryan Oct 28 '15 at 21:20
  • 1
    No, I just get 'None'... maybe I am doing something wrong when saving the files? – Larissa Leite Oct 28 '15 at 21:29
  • I suggest you use the mongo shell to verify that images are saved in the picture collection. Then verify that the post.images collection contains references to the pictures. – codeape Oct 29 '15 at 12:44
  • Another issue: (I've never used mongoengine before so there might be things I don't understand) In the [docs](http://docs.mongoengine.org/en/latest/apireference.html#mongoengine.fields.EmbeddedDocumentField) it says that EmbeddedDocumentField's document_type must be a type that inherits from EmbeddedDocument (ie. does not have it's own collection) - your Picture class inherits from Document. – codeape Oct 29 '15 at 12:47
  • Did anybody solve this? I have the same problem. – David Crook Jul 03 '17 at 17:25

1 Answers1

1

I believe you should do something like this:

class Picture(EmbeddedDocument):
    image = ImageField()

class Post(Document):
    ...
    comments = ListField(EmbeddedDocumentField('Comment'))
    user = ReferenceField('User', reverse_delete_rule='CASCADE')
    images = ListField(EmbeddedDocumentField('Picture'))

To store a picture, append the picture to the post.images collection and call post.save().

codeape
  • 97,830
  • 24
  • 159
  • 188