上传图片时创建动态路径 [英] Creating a dynamic path when I upload images
本文介绍了上传图片时创建动态路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为用户上传图片时创建动态路径。它的工作原理如下:
I'm trying to create a dynamic path for when my users upload images. It works something like this:
查看:
photo = Photo(...)
photo.save()
photo.original.save(filename, content)
型号:
album = models.ForeignKey(Album)
original = models.ImageField(upload_to="photos/%s/o" % str(album.id), max_length=200)
但是当我尝试这样做时,Django没有办法说。
But when I try to do this, Django says no way.
Exception Value:
'ForeignKey' object has no attribute 'id'
如何访问ForeignKey对象的模型成员以这种方式?
How can I access the model members of a ForeignKey object in this manner?
谢谢。
推荐答案
使用回调(callable):< a href =https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to =nofollow> https://docs.djangoproject.com /en/dev/ref/models/fields/#django.db.models.FileField.upload_to
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)
这篇关于上传图片时创建动态路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文