【问题标题】:Image upload through admin in Django在 Django 中通过管理员上传图片
【发布时间】:2014-05-09 22:05:13
【问题描述】:

我希望能够通过 Django 中的管理员上传图片。但是我遇到了一些困难

项目结构:

/Proj
   /Proj

   /static
      /img
         /albums
            /album1
               img1
            /album2
               img2

专辑类:

class Album(models.Model):
    title = models.CharField(max_length = 60)

    def __unicode__(self):
        return self.title

图像类:

class Image(models.Model):
    title = models.CharField(max_length = 60, blank = True, null = True)
    image = models.FileField(upload_to = get_upload_file_name)  <-- !!!!
    tags = models.ManyToManyField(Tag, blank = True)
    albums = models.ForeignKey(Album)
    width = models.IntegerField(blank = True, null = True)
    height = models.IntegerField(blank = True, null = True)
    created = models.DateTimeField(auto_now_add=True)

我认为我的image = models.FileField(upload_to = get_upload_file_name) 使用get_upload_file_name 方法将图像放置在正确的相册中。这是通过附加到我的MEDIA_ROOT 来完成的,即MEDIA_ROOT = os.path.join(BASE_DIR, 'static')

所以get_upload_file_name 方法应该这样做。但我不知道该怎么做。

我想在上传之前我需要先创建一个相册,然后我才能决定图片将进入哪个相册。此时有点迷失了。不确定我的Image 或Album 课程是否完整。感谢您的帮助!

【问题讨论】:

    标签: python django django-models django-admin


    【解决方案1】:

    您传递给upload_to 的函数必须具有以下形式:

    def get_upload_file_name(instance, filename):
        new_file_path_and_name = os.path.join(BASE_DIR, 'static', 'test.txt')
        return new_file_path_and_name
    

    instance 是您要保存的Image 模型的实例。这意味着它可以访问已填充的所有其他字段。 filename 是上载文件的原始名称。您可以选择使用 filename 或简单地返回您选择的另一个路径 + 名称。

    这方面的官方文档是here。

    【讨论】:

      猜你喜欢
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 2022-11-29
      相关资源
      最近更新 更多