开发者

Creating a dynamic path when I upload images

开发者 https://www.devze.com 2023-03-26 11:02 出处:网络
I\'m trying to create a dynamic path for when my users upload images. It works something like this: View:

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 'i开发者_运维问答d'

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

Thanks.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消