从 Django Document 对象获取文件名

Get file name from Django Document object

我有一个用于上传文件的表单。 我的 views.py 文件中的代码是:

def upload(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            # Redirect to the document list after POST

            return HttpResponse("Success!")
    else:
        form = DocumentForm()  # A empty, unbound form

        # Load documents for the list page
        documents = Document.objects.all()

        # Render list page with the documents and the form
        return render_to_response(
             'upload.html',
             {'documents': documents, 'form': form},
             context_instance=RequestContext(request)
             )

如何知道正在创建的文件名? 我正在使用 Django v. 1.9

在 python 中,您可以使用 name 属性获取它。,.

newdoc = request.FILES['docfile']
newdoc.name # file name

A​​ndv 如果您想在模板中看到代码

{% for document in documents %}
{{ document.file.filename }}
{% endfor }}

在模型对象中

newdoc = Document.objects.get(id=1)
newdoc.docfile.url # url of the file
newdoc.docfile.path # exact path