Django HTML5 - 下载文件

时间:2014-06-10 13:06:54

标签: python django upload

这是我的.html文件。它使用户能够上传文件并查看上传的文件列表,并下载列表中的文件 - 或者应该是!

问题是document.docfile.urldocfileFileField对象)没有返回所需的文件路径。所需的文件路径包含'media',但返回的文件路径为myapp / list /(...)

我的MEDIA_URL'media',即。

我怀疑这是一个不充分的解释,所以如果您需要更多信息,请告诉我。

<body>
    <!-- List of uploaded documents -->
    {% if documents %}
        <ul>
        {% for document in documents %}
            <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a> 
            <a href="{{ document.docfile.url }}" download="document.docfile.url">Download</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No documents.</p>
    {% endif %}

    <!-- Upload form. Note enctype attribute! -->
    <form action="{% url "list" %}" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <p>{{ form.non_field_errors }}</p>
        <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
        <p>
            {{ form.docfile.errors }}
            {{ form.docfile }}
        </p>
        <p><input type="submit" value="Upload" /></p>
    </form>

</body>

这是我的views.py:

def list(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 HttpResponseRedirect(reverse('myapp.views.list'))
    else:
        form = DocumentForm() # An 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(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

0 个答案:

没有答案