2014-05-09 80 views
0

上传我希望能够通过在Django管理员上传图片。但我有一些困难,图像通过管理员在Django

项目结构:

/Proj 
    /Proj 

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

Album类:

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方法应该这样做。但我不知道如何如此。

我想之前我可以上传我首先需要创建一个相册这样的话,我可以决定的图像会去哪个专辑。在这一点上有点失落。不知道我的ImageAlbum类甚至是完整的。谢谢您的帮助!!

回答

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 

instanceImage模型你要保存的实例。这意味着它可以访问已经填充的所有其他字段。 filename是上传文件的原始名称。您可以选择使用filename或者直接返回您选择的另一个路径+名称。

对此的官方文档是here

+0

感谢的人我感谢您的帮助! – Liondancer