zoukankan      html  css  js  c++  java
  • django 上传文件

    今天一大早爬起来就开始查找django 上传文件的例子。网上的例子不是写的太简单,就是不全面。现在终于自己解决了,并写了个小例子.

    demo 介绍:使用mysql数据库,把每次上传的文件按照日期分类存放,并且把文件路径上传到mysql数据库中。

    项目目录如下:



    下面上代码:

    myproject/urls.py:  用来存放整个项目的路径

    # -*- coding: utf-8 -*-
    from django.conf.urls import patterns, include, url
    from django.conf import settings
    from django.conf.urls.static import static
    from django.views.generic import RedirectView
    
    urlpatterns = patterns('',
    	(r'^myapp/', include('myproject.myapp.urls')),
    	(r'^$', RedirectView.as_view(url='/myapp/list/')), # Just for ease of use.
    ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    myproject/settings.py:部分代码如下   设置数据库,及文件存放路径

    import os
    PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
            'NAME': '',                      # Or path to database file if using sqlite3.
            # The following settings are not used with sqlite3:
            'USER': 'root',
            'PASSWORD': 'myproject',
            'HOST': '127.0.0.1',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
            'PORT': '3306',                      # Set to empty string for default.
            'default-character-set' :'utf8',
        }
    }
      
    HERE = os.path.dirname(__file__)   
    #MEDIA_ROOT =  HERE+STATIC_URL 
    
    
    
    MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
    
    # URL that handles the media served from MEDIA_ROOT. Make sure to use a
    # trailing slash.
    # Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
    MEDIA_URL = '/media/'

    myproject/myapp/forms.py    自定义form

    # -*- coding: utf-8 -*-
    from django import forms
    
    class DocumentForm(forms.Form):
        docfile = forms.FileField(
            label='Select a file',
            help_text='max. 42 megabytes'
        )
    

    myproject/myapp/models.py    模板文件,设置存储路径

    # -*- coding: utf-8 -*-
    from django.db import models
    
    class Document(models.Model):
        docfile = models.FileField(upload_to='documents/%Y/%m/%d')
    
    myproject/myapp/urls.py       app 路径文件
    # -*- coding: utf-8 -*-
    from django.conf.urls.defaults import patterns, url
    
    urlpatterns = patterns('myproject.myapp.views',
        url(r'^list/$', 'list', name='list'),
    )
    

    myproject/myapp/views.py   文件上传 view.py

    # -*- 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('myproject.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)
        )
    

    myproject/myapp/templates/myapp/list.html    文件列表及上传页面

    <!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> 
    

    数据库设计:

    建立一个myproject数据库,并建立一个myapp_document表。 设置两个字段id int类型;docfile  varchar类型。

    表结构如下:



    先存入几张图片:



    好了现在已经到了测试时间了,

    在浏览器中输入:http://localhost:8000/myapp/list

    运行结果如下:


    源码下载

    本文转自:点击打开链接










  • 相关阅读:
    SpringBoot学习(一)——Spring的发展
    layer插件学习——弹框(自定义页)
    layer插件学习——提示层
    layer插件学习——询问框
    layer插件学习——icon样式
    windows环境下搭建Java开发环境(二):Tomcat安装和配置
    windows环境下搭建Java开发环境(一):jdk安装和配置
    朋友(翻转树边权值比赛)——依然是思维
    S=∑1≤u<v≤nmex(u,v)
    Emergency Evacuation(最短下车时间)———(思维)
  • 原文地址:https://www.cnblogs.com/lixingle/p/3707722.html
Copyright © 2011-2022 走看看