0

I'm trying to create a dynamic path for when my users upload images. It works something like this:

View:

photo = Photo(...)
photo.save()

photo.original.save(filename, content)

Model:

album = models.ForeignKey(Album)
original = models.ImageField(upload_to="photos/%s/o" % str(album.id), max_length=200)

But when I try to do this, Django says no way.

Exception Value:    
'ForeignKey' object has no attribute 'id'

How can I access the model members of a ForeignKey object in this manner?

Thanks.

Brian D
  • 9,863
  • 18
  • 61
  • 96

1 Answers1

2

Use a callback (callable): https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to

def fancy_path(instance, filename):
    return 'fancy_path/file_%s.xml' % self.instance.album.id

original = models.ImageField(upload_to=fancy_path, max_length=200)
Willian
  • 2,385
  • 15
  • 17
  • 1
    That's about it. @Willian hit the nail on the head. The only thing you have to ensure is that your object has a value for that album FK _before_ the image is processed. – Owen Nelson Aug 06 '11 at 00:40
  • Yeah, I was careful for that part, thus the double save above. – Brian D Aug 08 '11 at 05:44