zjxplq 发表于 2013-1-15 02:09:55

在django中动态设置上传路径

参考于: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)...
页: [1]
查看完整版本: 在django中动态设置上传路径