在Django 1.3中,用户上传一个“hello world”应用程序所需的最少示例代码是什么?


当前回答

它可能会帮助你: 在models.py中创建一个文件字段

上传文件(在admin.py中):

def save_model(self, request, obj, form, change):
    url = "http://img.youtube.com/vi/%s/hqdefault.jpg" %(obj.video)
    url = str(url)

    if url:
        temp_img = NamedTemporaryFile(delete=True)
        temp_img.write(urllib2.urlopen(url).read())
        temp_img.flush()
        filename_img = urlparse(url).path.split('/')[-1]
        obj.image.save(filename_img,File(temp_img)

并在模板中使用该字段。

其他回答

你可以参考Fine Uploader中的服务器示例,它有django版本。 https://github.com/FineUploader/server-examples/tree/master/python/django-fine-uploader

它非常优雅,最重要的是,它提供了特色的js lib。Template不包含在服务器示例中,但是你可以在它的网站上找到demo。 精美上传:http://fineuploader.com/demos.html

django-fine-uploader

views.py

UploadView将post和delete请求分派给各自的处理程序。

class UploadView(View):

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(UploadView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        """A POST request. Validate the form and then handle the upload
        based ont the POSTed data. Does not handle extra parameters yet.
        """
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_upload(request.FILES['qqfile'], form.cleaned_data)
            return make_response(content=json.dumps({ 'success': True }))
        else:
            return make_response(status=400,
                content=json.dumps({
                    'success': False,
                    'error': '%s' % repr(form.errors)
                }))

    def delete(self, request, *args, **kwargs):
        """A DELETE request. If found, deletes a file with the corresponding
        UUID from the server's filesystem.
        """
        qquuid = kwargs.get('qquuid', '')
        if qquuid:
            try:
                handle_deleted_file(qquuid)
                return make_response(content=json.dumps({ 'success': True }))
            except Exception, e:
                return make_response(status=400,
                    content=json.dumps({
                        'success': False,
                        'error': '%s' % repr(e)
                    }))
        return make_response(status=404,
            content=json.dumps({
                'success': False,
                'error': 'File not present'
            }))

forms.py

class UploadFileForm(forms.Form):

    """ This form represents a basic request from Fine Uploader.
    The required fields will **always** be sent, the other fields are optional
    based on your setup.
    Edit this if you want to add custom parameters in the body of the POST
    request.
    """
    qqfile = forms.FileField()
    qquuid = forms.CharField()
    qqfilename = forms.CharField()
    qqpartindex = forms.IntegerField(required=False)
    qqchunksize = forms.IntegerField(required=False)
    qqpartbyteoffset = forms.IntegerField(required=False)
    qqtotalfilesize = forms.IntegerField(required=False)
    qqtotalparts = forms.IntegerField(required=False)

唷,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:GitHub的源代码除了1.3之外,还实现了Django 1.4。尽管改动很少,但下面的教程对于1.4也是有用的。

更新2013-05-10:Django 1.5在GitHub的实现。url .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,感谢daavve和nerogit

项目树

一个基本的Django 1.3项目,包含单个应用程序和用于上传的媒体/目录。

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管理文件的第一行。还记得设置数据库并将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_ROOT存储到media/documents/2011/12/24/。参见FileField参考。

# -*- 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

为了更好地处理上传,您需要一个表单。这个表单只有一个字段,但这就足够了。详细信息请参阅表单FileField参考。

# -*- 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

所有的奇迹都发生在这里。注意如何请求。文件被处理。对我来说,很难发现这个请求。FILES['docfile']可以保存到模型中。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. 项目url: myproject/ URLs .py

Django默认不提供MEDIA_ROOT服务。这在生产环境中是很危险的。但在发展阶段,我们可以缩短。注意最后一行。这一行使Django能够提供来自MEDIA_URL的文件。这只在开发阶段有效。

详情请参见django.conf.urls.static.static引用。另请参阅有关提供媒体文件的讨论。

# -*- 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. 应用url: myproject/myapp/ URLs .py

要使视图可访问,必须为它指定url。这里没什么特别的。

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

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

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

最后一部分:模板列表和下面的上传表单。表单必须将enctype-attribute设置为“multipart/form-data”,并将method设置为“post”,这样才能上传到Django。有关详细信息,请参阅文件上传文档。

FileField有许多可以在模板中使用的属性。例如模板中的{{document.docfile.url}}和{{document.docfile.name}}。有关这些的更多信息,请参见在模型中使用文件的文章和文件对象文档。

<!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/,可以从列表中打开。

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

以亨利为例:

import tempfile
import shutil

FILE_UPLOAD_DIR = '/home/imran/uploads'

def handle_uploaded_file(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=FILE_UPLOAD_DIR)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
    return filepath

你可以在上传文件对象的视图中调用handle_uploaded_file函数。这将在文件系统中保存具有唯一名称的文件(以原始上传文件的文件名作为前缀),并返回所保存文件的完整路径。您可以将该路径保存在数据库中,稍后对该文件进行处理。

Demo

参见github repo,适用于Django 3

一个简单的Django文件上传示例

1. 创建一个django项目

运行startproject::

$ django-admin.py startproject sample

现在创建了一个文件夹(示例)。

2. 创建应用程序

创建一个应用::

$ cd sample
$ python manage.py startapp uploader

现在创建一个包含这些文件的文件夹(uploader):

uploader/
  __init__.py
  admin.py
  app.py
  models.py
  tests.py
  views.py
  migrations/
    __init__.py

3.更新settings.py

在sample/settings.py中添加'uploader'到INSTALLED_APPS,并添加MEDIA_ROOT和MEDIA_URL,即::

INSTALLED_APPS = [
    'uploader',
    ...<other apps>...      
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

4. 更新urls . py

在sample/urls.py中添加::

...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views

urlpatterns = [
    ...<other url patterns>...
    path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. 更新models.py

更新上传/ models.py::

from django.db import models
class Upload(models.Model):
    upload_file = models.FileField()    
    upload_date = models.DateTimeField(auto_now_add =True)

6. 更新views.py

更新上传/ views.py::

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
    model = Upload
    fields = ['upload_file', ]
    success_url = reverse_lazy('fileupload')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['documents'] = Upload.objects.all()
        return context

7. 创建模板

创建文件夹sample/uploader/templates/uploader

创建文件upload_form.html ie sample/uploader/templates/uploader/upload_form.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>Django File Upload</h1>
    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Submit</button>
    </form><hr>
    <ul>
    {% for document in documents %}
        <li>
            <a href="{{ document.upload_file.url }}">{{ document.upload_file.name }}</a>
            <small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
        </li>
    {% endfor %}
    </ul>
</div>

8. Syncronize数据库

同步数据库和runserver::

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

访问http://localhost: 8000 /

我也有类似的要求。网上的大多数例子都要求创建模型和表单,我不想使用。这是我的最终代码。

if request.method == 'POST':
    file1 = request.FILES['file']
    contentOfFile = file1.read()
    if file1:
        return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})

在HTML中我写了:

{% block content %}
    <h1>File content</h1>
    <form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
         {% csrf_token %}
        <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
        <input type="submit" value="Upload" />
    </form>
    {% endblock %}

下面是显示文件内容的HTML:

{% block content %}
    <h3>File uploaded successfully</h3>
    {{file.name}}
    </br>content = {{contentOfFile}}
{% endblock %}