django - 如何在Django中上传文件?

标签 django file upload

关闭。这个问题需要更多focused .它目前不接受答案。












想改善这个问题吗?更新问题,使其仅关注一个问题 editing this post .

5年前关闭。



Improve this question




作为 Django 的新手,我很难在 Django 1.3 中制作上传应用程序。我找不到任何最新的示例/片段。有人可以发布一个最小但完整的(模型、 View 、模板)示例代码吗?

最佳答案

呼,Django 文档确实没有很好的例子。我花了 2 个多小时来挖掘所有部分以了解这是如何工作的。有了这些知识,我实现了一个项目,可以上传文件并将它们显示为列表。要下载该项目的源代码,请访问 https://github.com/axelpale/minimal-django-file-upload-example或克隆它:

> git clone https://github.com/axelpale/minimal-django-file-upload-example.git

2013-01-30 更新:除了 1.3 之外,GitHub 上的源代码还实现了 Django 1.4。尽管更改很少,但以下教程对 1.4 也很有用。

2013-05-10 更新:在 GitHub 上实现 Django 1.5。 urls.py 中的重定向和 list.html 中 url 模板标签的使用的细微变化。感谢 hubert3为了努力。

2013-12-07 更新: GitHub 支持 Django 1.6。在 myapp/urls.py 中更改了一项导入。感谢 Arthedian .

2015-03-17 更新: GitHub 支持 Django 1.7,感谢 aronysidoro .

2015-09-04 更新: GitHub 支持 Django 1.8,感谢 nerogit .

2016-07-03 更新: GitHub 支持 Django 1.9,感谢 daavvenerogit

项目树

一个基本的 Django 1.3 项目,带有单个应用程序和用于上传的 media/目录。
minimal-django-file-upload-example/
    src/
        myproject/
            database/
                sqlite.db
            media/
            myapp/
                templates/
                    myapp/
                        list.html
                forms.py
                models.py
                urls.py
                views.py
            __init__.py
            manage.py
            settings.py
            urls.py

1. 设置:myproject/settings.py

要上传和提供文件,您需要指定 Django 存储上传文件的位置以及 Django 提供文件的 URL。 MEDIA_ROOT 和 MEDIA_URL 默认在 settings.py 中,但它们是空的。请参阅 Django Managing Files 中的第一行详情。记住还要设置数据库并将 myapp 添加到 INSTALLED_APPS
...
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'database.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
...
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
...
INSTALLED_APPS = (
    ...
    'myapp',
)

2.模型:myproject/myapp/models.py

接下来您需要一个带有 FileField 的模型。这个特定的字段存储文件,例如到 media/documents/2011/12/24/基于当前日期和 MEDIA_ROOT。见 FileField reference .
# -*- coding: utf-8 -*-
from django.db import models

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

3. 表单:myproject/myapp/forms.py

为了很好地处理上传,您需要一个表单。此表单只有一个字段,但这已经足够了。见 Form FileField reference详情。
# -*- coding: utf-8 -*-
from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
        help_text='max. 42 megabytes'
    )

4.查看:myproject/myapp/views.py

所有魔法发生的地方。注意如何request.FILES被处理。对我来说,真的很难发现 request.FILES['docfile']可以像这样保存到models.FileField。模型的 save() 自动处理文件到文件系统的存储。
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm

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() # 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(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

5. 项目网址:myproject/urls.py

Django 默认不提供 MEDIA_ROOT 服务。这在生产环境中会很危险。但在开发阶段,我们可以缩短。注意最后一行。该行使 Django 能够从 MEDIA_URL 提供文件。这仅适用于开发阶段。

django.conf.urls.static.static reference详情。另见 this discussion about serving media files .
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    (r'^', include('myapp.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

6. 应用网址:myproject/myapp/urls.py

要使 View 可访问,您必须为其指定 url。这里没什么特别的。
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

urlpatterns = patterns('myapp.views',
    url(r'^list/$', 'list', name='list'),
)

7. 模板:myproject/myapp/templates/myapp/list.html

最后一部分:列表模板及其下方的上传表单。表单必须将 enctype-attribute 设置为“multipart/form-data”,并将方法设置为“post”,才能上传到 Django。见 File Uploads documentation详情。

FileField 有许多可以在模板中使用的属性。例如。 {{ document.docfile.url }} 和 {{ document.docfile.name }} 与模板中的一样。在 Using files in models article 中查看有关这些的更多信息和 The File object documentation .
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Minimal Django File Upload Example</title>   
    </head>
    <body>
    <!-- List of uploaded documents -->
    {% if documents %}
        <ul>
        {% for document in documents %}
            <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</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>
</html> 

8. 初始化

只需运行syncdb 和runserver。
> cd myproject
> python manage.py syncdb
> python manage.py runserver

结果

最后,一切准备就绪。在默认的 Django 开发环境中,可以在 localhost:8000/list/ 看到上传的文档列表。 .今天文件上传到/path/to/myproject/media/documents/2011/12/17/,可以从列表中打开。

我希望这个答案能帮助别人,就像它对我的帮助一样。

关于django - 如何在Django中上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5871730/

相关文章:

c++ - 为什么我的程序中的第二个 while 循环在它前面有一个 while 循环时不起作用?

android - 在 multipart retrofit2 中上传图像数组

angularjs - 使用 multer、ng-file-upload、Angular 和 Node 上传多个文件,并将动态表单数据绑定(bind)到每个文件

django - 破译 psycopg2 :OperationalError 的特例

django - 从 heroku 访问 s3 内容时,AWS 访问 key 显示在浏览器 url 中

android - 内部存储和文件?

c++ - 用于读取文本文件 C++ 的标准循环

php - 上传和调整图像大小时PNG黑色背景

python - Apache/mod_wsgi 中的 Django 部署问题。导入错误 : Could not import settings 'site.settings'

python - 从另一个模型向序列化器添加额外的字段