トップ 差分 一覧 ping ソース 検索 ヘルプ PDF RSS ログイン

Django Fileアップロード例



目次



記事一覧

キーワード

Django Fileアップロード例

[Django][Python]

 fileuptest/views.py

from django.http import HttpResponse
from django.template import Context, loader
from django.forms import *

def index(request):
    msg = ''
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            updir = r'c:\\website\\django\\mysite\\upload\\' + form.cleaned_data['title']
            destination = open(updir, 'wb+')
            upfile = request.FILES['file']
            for chunk in upfile.chunks():
                destination.write(chunk)
            destination.close()
            msg = 'Uploaded.'
    else:
        form = UploadFileForm()

    t = loader.get_template('fileuptest/index.html')
    c = Context()
    c['form'] = form
    c['msg'] = msg
    return HttpResponse(t.render(c))

class UploadFileForm(Form):
    title = CharField(max_length=50)
    file  = FileField()

 template/fileuptest/index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <script type="text/javascript">
  </script>
</head>
<body>
  {{msg}}
  <form enctype="multipart/form-data" action='/fileuptest/' method='POST'>
    <table>
    {{form}}
    </table>    
    <input type='submit' value=" 添 付 ">
  </form>
</body>
</html>

 結果



YAGI Hiroto (piroto@a-net.email.ne.jp)
twitter http://twitter.com/pppiroto

Copyright© 矢木 浩人 All Rights Reserved.