使用动态路径

时间:2016-02-25 15:46:39

标签: django upload

我正在尝试上传文件并在媒体文件夹中组织目录结构。具体来说,我希望上传根据模型中的一个值创建子文件夹。我面临的问题是在视图中我向实例添加信息(在我的示例代码中,这是相关的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)

1 个答案:

答案 0 :(得分:2)

将返回上传路径的函数需要2个参数,即:instancefilename。您需要在此类之外定义此函数,并将此函数提供给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,以下是您最有可能获得的错误:

  

ValueError:在categories.models中找不到函数get_upload_to。

     

请注意,由于Python 2的限制,您无法序列化未绑定的方法函数(例如,在同一个类体中声明和使用的方法)。请将该功能移动到主模块主体中以使用迁移。