| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Django Fileアップロード例

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

Django Fileアップロード例

Django | Python |

fileuptest/views.py

  1. from django.http import HttpResponse
  2. from django.template import Context, loader
  3. from django.forms import *
  4.  
  5. def index(request):
  6. msg =
  7. if request.method == 'POST':
  8. form = UploadFileForm(request.POST, request.FILES)
  9. if form.is_valid():
  10. updir = r'c:\\website\\django\\mysite\\upload\\' + form.cleaned_data['title']
  11. destination = open(updir, 'wb+')
  12. upfile = request.FILES['file']
  13. for chunk in upfile.chunks():
  14. destination.write(chunk)
  15. destination.close()
  16. msg = 'Uploaded.'
  17. else:
  18. form = UploadFileForm()
  19.  
  20. t = loader.get_template('fileuptest/index.html')
  21. c = Context()
  22. c['form'] = form
  23. c['msg'] = msg
  24. return HttpResponse(t.render(c))
  25.  
  26. class UploadFileForm(Form):
  27. title = CharField(max_length=50)
  28. file = FileField()

template/fileuptest/index.html

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3. <head>
  4. <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <script type="text/javascript">
  6. </script>
  7. </head>
  8. <body>
  9. テンプレート:Msg
  10. <form enctype="multipart/form-data" action='/fileuptest/' method='POST'>
  11. <table>
  12. テンプレート:Form
  13. </table>
  14. <input type='submit' value=" 添 付 ">
  15. </form>
  16. </body>
  17. </html>

結果

0385 fileup form01.jpg