Djangoでpost_image.htmlで参照、POSTされたイメージをdisp_image.htmlで表示するプログラムを作成しようとした結果以下のようなエラーがでました。どのように直したら問題が解決しますか?
Traceback (most recent call last): File "/home/yuyonod/anaconda3/envs/mlapi/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/yuyonod/anaconda3/envs/mlapi/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/yuyonod/anaconda3/envs/mlapi/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/yuyonod/work/mlapi/hawkowl/hawkowl/views.py", line 22, in dispImage if request.method == 'POST' and request.FILES['image'] and (request.FILES['image'].content_type == "image/png" or request.FILES['image'].content_type == "image/jpeg"): File "/home/yuyonod/anaconda3/envs/mlapi/lib/python3.8/site-packages/django/utils/datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'image' [17/Jun/2020 10:10:51] "POST /disp_image HTTP/1.1" 500 80966
djangoのviews.py
from django.http import HttpResponse, HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from hashlib import md5 def post_image(request): return render(request, 'post_image.html') def dispImage(request): if request.method == 'POST' and request.FILES['image'] and (request.FILES['image'].content_type == "image/png" or request.FILES['image'].content_type == "image/jpeg"): # 画像の拡張子 extension = ".jpg" if request.FILES['image'].content_type == "image/png": extension = ".png" # ファイル名 filename = md5(request.FILES['image'].name.encode('utf-8')).hexdigest() + extension # ファイルパス filepath = 'static/' + filename # 画像データを image へ書き写す image = open(filepath, 'wb') for chunk in request.FILES['image'].chunks(): image.write(chunk) return render(request, 'display_image.html', {'filepath': filepath}) else: return HttpResponseRedirect('/post_image')
post_image.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form action="/disp_image" method='POST' enctype='multipart/form-data'> {% csrf_token %} <input type="file" name='image'> <input type="submit" value='send'> </form> </body> </html>
disp_image.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h2>hoge</h2> <img src="{{filepath}}" alt=""> <h1></h1> </body> </html> コード
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。