django将文件保存到文件夹中

时间:2014-07-16 11:21:08

标签: python django

我想将文件保存到单独的文件夹中,但文件夹名称我将从我不知道的表单中获取它。但我现在有了工作表格,将保存到user_(某事物)。

任何人都可以告诉我如何定义模型类和视图以获取文件夹名称和我上传保存的文件自动保存到单独的文件夹中。

models.py

def content_file_name(instance, filename):
    return "user_{id}/{file}".format(id=instance, file=filename)

class Audio(models.Model):
    audiofile = models.FileField(upload_to=content_file_name)

views.py

def saved_file(request):
    # Handle file upload
    if request.method == 'POST':
        form = AudioForm(request.POST, request.FILES)
        if form.is_valid():
            newaudio = AudioForm()
            newaudio = Audio(audiofile = request.FILES['audiofile'])
            newaudio.save()

            #This is for redirect to the file save_list after post 
            return HttpResponseRedirect(reverse('app.views.saved_file'))
    else:
        form = AudioForm()

    # Load documents for the save_list page
    showfiles = Audio.objects.all()
    return render_to_response(
        'audio/file_upload.html',
        {'showfiles': showfiles, 'form': form},
        context_instance=RequestContext(request)
    )

1 个答案:

答案 0 :(得分:0)

您可以将文件夹名称作为模型的一部分,然后相应地修改content_file_name函数吗?

def content_file_name(instance, filename):
    return "user_{id}/{folder}/{file}".format(id=instance, folder=instance.folder_name, file=filename)

class Audio(models.Model):
    audiofile = models.FileField(upload_to=content_file_name)
    folder_name = models.CharField(max_length=1000)