我尝试使用在照片上传期间指定的图库名称在媒体中保存图像。我的代码如下:
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
class Gallery(models.Model):
name = models.CharField(max_length=128)
upload_date = models.DateField()
class Meta:
verbose_name_plural = "galleries"
class Photo(models.Model):
Name = models.CharField(max_length=128)
File = models.FileField()
PhotoGallery = models.ForeignKey(Gallery, on_delete=models.CASCADE)
def save(self, *args, **kwargs):
self.File.upload_to = "{media}/photohouse/{gallery}".format(media=settings.MEDIA_ROOT,
gallery=self.PhotoGallery.name)
super(Photo, self).save(*args, **kwargs)
图像仍然上传到根媒体。我做错了什么?
答案 0 :(得分:2)
upload_to
需要可调用并指定为模型字段的一部分。
def photo_upload_to(instance, filename):
return '{media}/photohouse/{gallery}/{filename}'.format(
media=settings.MEDIA_ROOT,
gallery=instance.PhotoGallery.name,
filename=filename)
class Photo(models.Model):
....
File = models.FileField(upload_to=photo_upload_to)