使用动态路径将文件上传到 Django

Upload file to Django with dynamic path

我正在尝试上传文件并组织媒体文件夹中的目录结构。具体来说,我希望上传基于模型中的值之一创建子文件夹。我面临的问题是,在视图中我向实例添加了信息(在我的示例代码中,这是相关的 profile)。我想将此信息用于子文件夹,但它在我的模型中不存在,直到上传后的保存...

将信息放入 Upload 以便创建子文件夹的适当方法是什么?

谢谢

型号:

class Upload(models.Model):
    file = models.FileField(upload_to="upload/")
    profile = models.ForeignKey(Profile, blank=True, null=True)

    def get_upload_to(self, field_attname):
        return 'upload/%d' % self.profile

查看:

def profile(request, profile_slug):
    profile = Profile.objects.get(slug=profile_slug)
    context_dict['profile'] = profile
    if request.method=="POST":
            for file in request.FILES.getlist('file'):
                    upload = UploadForm(request.POST, request.FILES)
                    if upload.is_valid():
                            newupload = upload.save(commit=False)
                            newupload.profile = profile
                            newupload.save()
    else:
        pass

    upload=UploadForm()
    context_dict['form'] = upload

    return render(request, 'app/profile.html', context_dict)

解决方案,感谢 xyres:

型号:

def get_upload_to(instance, filename):
    return 'upload/%s/%s' % (instance.profile, filename)

class Upload(models.Model):
    file = models.FileField(upload_to=get_upload_to)
    profile = models.ForeignKey(Profile, blank=True, null=True)

查看:

def profile(request, profile_slug):
    profile = Profile.objects.get(slug=profile_slug)
    context_dict['profile'] = profile
    if request.method=="POST":
        upload = UploadForm(request.POST, request.FILES)
        if upload.is_valid():
            for f in request.FILES.getlist('file'):
                Upload.objects.create(file=f, profile=profile)
        return redirect(reverse('profile')
    else:
        pass

    return render(request, 'app/profile.html', context_dict)

return上传路径的函数有两个参数,即:instancefilename。您需要在此 class 之外定义此函数并将此函数提供给 upload_to 选项。

这就是您需要重写代码的方式:

def get_upload_to(instance, filename):
    return 'upload/%d/%s' % (instance.profile, filename)


class Upload(models.Model):
    file = models.FileField(upload_to=get_upload_to)
    profile = models.ForeignKey(Profile, blank=True, null=True)

编辑:

如果您想知道为什么 get_upload_to 不能在 class 中定义,下面是您很可能遇到的错误:

ValueError: Could not find function get_upload_to in categ.models.

Please note that due to Python 2 limitations, you cannot serialize unbound method functions (e.g. a method declared and used in the same class body). Please move the function into the main module body to use migrations.