Django文件上传具有唯一名称

时间:2013-11-12 17:11:33

标签: django file-upload django-forms

我尝试按照Django文档在Django上传文件。

def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

但是当我上传它时它会覆盖name.txt文件。如何确保该文件夹中有唯一的名称? (它可以保存为名称(1).txt)

P.S:Django在使用File字段保存模型时处理它。但是,我使用表单,我需要手动处理它。

由于

1 个答案:

答案 0 :(得分:0)

如果您使用uuid库

,您将获得唯一ID
import uuid

def handle_uploaded_file(f):

    name = 'some/file/%s.txt' % uuid.uuid1()

    with open(name, 'wb+') as destination:
       for chunk in f.chunks():
            destination.write(chunk)

http://docs.python.org/2/library/uuid.html

相关问题