如何在Django上传照片基于其他模型领域的图库名称?

时间:2016-02-04 18:16:14

标签: python django

我尝试使用在照片上传期间指定的图库名称在媒体中保存图像。我的代码如下:

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)

图像仍然上传到根媒体。我做错了什么?

1 个答案:

答案 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)