在 django 1.4 中设置上传路径的最佳做法是什么?我有一个这样的模型
def upload_image(instance, filename):
return os.path.join(instance.slug, filename)
class Book(models.Model):
...
...
image = models.ImageField(upload_to=upload_image)
def admin_image(self):
return "<img src='%s' />" % self.image
....
使用 settings.py
PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = PROJECT_DIR.rsplit(os.sep, 1)[0]
MEDIA_ROOT = os.path.join(ROOT_DIR, 'books', 'static', 'books')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
和 admin.py 像这样
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'admin_image')
因此,最后,我将图像正确保存到 /root-of-project/books/static/books/programming-java/wall.jpg,但是,数据库中保存的路径是“programming-java/wall.jpg”。 jpg”,我每次显示图像时都必须连接前缀 '/static/books/'