Python 3.6.5
Django 2.0.6
Django REST FrameworkのAPIに対してjQueryを利用したAjaxでinputタグに読み込んだ画像ファイルを送信したところ、
データがrequest.POSTのkeyにMultiValueDictとして入力されてしまってrequest.POST.get()で取得することが出来ません。
どうしたら通常の様なkeyに対するvalueとしてrequest.POSTへ入力される様になるのでしょうか。
データの送信処理自体はページからデータをAPIに対してjQueryを利用したAjaxでサーバへ送信して登録するという処理を既に作成していて、
Ajaxで送信されたデータが通常のrequest.POST.get()で取得可能な状態であることを確認してから流用しています。
実行時の出力
10
None
<QueryDict: {'[object Object]': ['']}>
<MultiValueDict: {'[object Object]': ['']}>
(省略)
AttributeError: 'MultiValueDict' object has no attribute 'iteritems'
AjaxにcontentType: 'multipart/form-data',を追加した場合、
10
None
<QueryDict: {}>
<MultiValueDict: {}>
(中略)
multipartparser.py", line 72, in init
raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary.decode())
AttributeError: 'NoneType' object has no attribute 'decode'
というエラーが幾つも出力されます。
JavaScript
1pcreate.js 2var input_file_change = function () { 3 input_file = document.getElementById('input_file'); 4 files = input_file.files; 5 if (files[0] != 'undefined') { 6 var fd = new FormData(); 7 var id = document.getElementById('photo_id').value; 8 for (var i = 0; i < files.length; i++) { 9 var file = files[i]; 10 11 fd.append('file', file); 12 } 13 14 $.ajax({ 15 url: 'http://localhost:8000/api/submit_picture/', 16 type: 'POST', 17 data: { 18 'files': fd, 19 'id': id, 20 }, 21 processData: false, 22 dataType: 'json', 23// contentType: 'multipart/form-data', 24 success: function(response) { 25 console.log('success'); 26 }, 27 error: function(e, x, r) { 28 console.log(e); 29 } 30 }); 31 } 32};
HTML
1pcreate.html 2<div class="col"> 3 <button class="btn btn-outline-primary" id="add_picture">画像の追加</button> 4 <form method="POST" enctype="multipart/form-data" id="save_picture"> 5 <input type="file" name="files[]" style="display: none" id="input_file" multiple> 6 <input type="hidden" value="{{ photo_id }}" id="photo_id"> 7 {% csrf_token %} 8 <input type="submit" style="display: block" id="submit_picture" name="submit_picture"> 9 </form> 10</div> 11
Python
1views.py 2class PCreate(generic.TemplateView): 3 template_name = 'photo_app/pcreate.html' 4 5 def get_context_data(self, **kwargs): 6 7 context = super(PCreate, self).get_context_data(**kwargs) 8 context['photo_id'] = '' 9 return context 10 11class PictureSave(viewsets.ModelViewSet): 12 13 queryset = Photo.objects.all() 14 serializer_class = PictureSaveSerializer 15 16 def create(self, request, *args, **kwargs): 17 18 json_ary = [] 19 if request.method == 'POST': 20 login_user_id = request.user.id 21 photo_id = request.POST.get('id') 22 files = request.POST.get('files') 23 24 print(login_user_id) 25 print(photo_id) 26 print(request.POST) 27 print(files) 28 29 for filename, file in request.FILES.iteritems(): 30 print(file) 31 dict = [] 32 33 photoObject = Photo( 34 title=request.FILES[filename].name, 35 image=file, 36 user_id = login_user_id, 37 photo_id=id 38 ) 39 photoObject.save() 40 41 dict.append({ 42 'id':'%s' % photoObject.id, 43 'filename': request.FILES[filename].name, 44 'file': file, 45 }) 46 47 json_ary.append(dict) 48 49 return JsonResponse({"data":json_ary})
Python
1models.py 2def get_upload_to(instance, filename): 3 name = str(uuid.uuid4()).replace('-', '') 4 extension = os.path.splitext(filename)[-1] 5 return os.path.join(str(instance.photobook_id.id), name, extension) 6 7class Photo(models.Model): 8 9 use_in_migrations = True 10 11 # ユーザーID 12 user_id = models.PositiveIntegerField(_('ユーザーID'), default=0, blank=False) 13 # 画像タイトル 14 title = models.CharField(max_length=255,) 15 # 画像データ 16 image = models.ImageField(upload_to=get_upload_to, null=True, blank=True,) 17 # 登録日時 18 date_joined = models.DateTimeField(_('登録日時'), default=timezone.now) 19 20 class Meta: 21 app_label = 'photobook_app'
Python
1serializer.py 2class PictureSaveSerializer(serializers.ModelSerializer): 3 4 class Meta: 5 model = Photo 6 fields = '__all__'
Python
1urls.py 2#写真の追加処理 3router.register(r'submit_picture', PictureSave) 4 5urlpatterns = [ 6 path('pcreate/', views.PCreate.as_view(), name='pcreate'), 7]
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。