六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 54|回复: 0

在django中动态设置上传路径

[复制链接]

升级  56%

6

主题

6

主题

6

主题

童生

Rank: 1

积分
28
 楼主| 发表于 2013-2-7 08:47:46 | 显示全部楼层 |阅读模式
参考于:http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/

FileField或ImageField的参数upload_to可以是一个可执行的对象。这个可执行的函数可传入当前model实例与上传文件名,且必须返回一个路径。
下面是一个实例:
 
import osfrom django.db import modelsdef get_image_path(instance, filename):    return os.path.join('photos', str(instance.id), filename)class Photo(models.Model):    image = models.ImageField(upload_to=get_image_path) get_image_path是一个可执行的对象(实际上是函数)。它从Photo的实例中获取id,并将它用于上传路径中。图像上传路径如:photos/1/kitty.jpg
可以使用实例中的任何字段或相关models中的字段。
为了使用get_image_path可用于多个models,可以作如下改进:
 
def get_image_path(path, attribute):    def upload_callback(instance, filename):        return '%s%s/%s' % (path, unicode(slugify(getattr(instance, attribute))), filename)    return upload_callback...#Model definitionsclass Photo(models.Model):    name = models.CharField()    image = models.ImageField(upload_to = get_image_path('uploads/', 'name'))class Screenshot(models.Model):    title = models.CharField()    image = models.ImageField(upload_to = get_image_path('uploads/', 'title'))  
为了更灵活,还可以作如下改进:
 
def get_image_path(path, attribute):    def upload_callback(instance, filename):        attributes = attribute.split('.')        for attr in attributes:            try:                instance = getattr(instance,attr)            except:                print 'attribute error'        return '%s%s/%s' % (path,unicode(instance),filename)    return upload_callbackclass Block(models.Model):    description = models.CharField(max_length=255) class Building(models.Model):    block = models.ForeignKey(Block)    address = models.CharField(max_length=255)    image = models.ImageField(upload_to=get_image_path('uploads/','block.description')) 作了如此改进后,可以方便的设置与当前实例相关的models中字段了。
 

注意的是如果你使用id,得先确定model实例在上传文件之前保存了,否则id会不存在。为了解决这个情况,在view中可以如下操作
...    if request.method == 'POST':        form = PhotoForm(request.POST, request.FILES)        if form.is_valid():            photo = Photo.objects.create()            image_file = request.FILES['image']            photo.image.save(image_file.name, image_file)...
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表