Creating a dynamic path when I upload images

前提是你 提交于 2019-12-23 05:50:13

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/6962634/creating-a-dynamic-path-when-i-upload-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!