【问题标题】:Dynamic File Path for image in DjangoDjango中图像的动态文件路径
【发布时间】:2012-08-15 16:17:30
【问题描述】:

我正在尝试在 django 中生成动态文件路径。我想做一个这样的文件系统

hierarchy:
 --user_12
  --channel_14
   --program 2
    --image1.jpg
    --image2.jpg
   --program 1
    --image1.jpg
    --image2.jpg
 --user_14
  --channel_13
   --program 1
    --image1.jpg
    --image2.jpg

当用户要上传图片时,它会将图片上传到相应的程序文件夹。如果程序文件夹没有创建,它会自动创建一个文件夹并存储图片..

我的图像路径将如下所示:media/images/john/johnchannel/birthday/img1.jpg(其中 john=user,johnchannel=channel,birthday=program,images 是所有图像文件应该存放的预创建文件夹存储) 我是 django 的新手。需要紧急帮助。

【问题讨论】:

标签: django django-media


【解决方案1】:

你在寻找这样的东西吗?

misc.py

def get_upload_path(instance, filename):
    """ creates unique-Path & filename for upload """
    ext = filename.split('.')[-1]
    filename = "%s%s.%s" % ('img', instance.pk, ext)

    return os.path.join(
        'images', instance.user.username, instance.channel, instance.something, filename
        #images/     john/                johnchannel/       birthday/          img1.jpg
    )

models.py

from misc import get_upload_path

class MyThing(models.Model):
    user = models.ForeignKey(User)
    channel = models.CharField(max_length=100) # johnchannel
    something = models.CharField(max_length=100) # birthday
    img = models.ImageField(upload_to=get_upload_path)

【讨论】:

  • 我的图片路径如下所示:media/images/john/johnchannel/birthday/img1.jpg(其中 john=user,johnchannel=channel,birthday=program)
【解决方案2】:

在 Django 模型中使用 ImageField 时,可以在 upload_to 关键字参数中指定可调用对象:See the FileField docs here

因此,创建一个您将指向 upload_to 的函数,它可以根据需要生成所有子目录。

【讨论】:

    猜你喜欢
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 2019-10-24
    • 2019-05-28
    • 2012-10-04
    • 1970-01-01
    相关资源
    最近更新 更多