Home > Software engineering >  Django API rejects file
Django API rejects file

Time:01-06

I'm trying to send a csv file to my Django API and response with process data, but when I send it, I get the error:

django.utils.datastructures.MultiValueDictKeyError: 'file'

this is my react code:

import { useState } from 'react';
import './App.css';

function App() {

  const [file, setFile] = useState(null);

  const uploadFiles = e =>{
    setFile(e);
  }

  const insertFile = async() => {
    const f = new FormData();
    f.append("file", file);

    await fetch(
      'http://localhost:8000/api/',
      {
        method: 'POST',
        headers: { 'content-type': 'multipart/form-data' },
        body: f,
      })
      .then((response) => response.json())
      .then((data)=>{
        console.log(data);
      })
      .catch(error=>{
        console.log(error);
      });

  }

  return (
    <>
      <input type="file" name="file" onChange={(e)=>uploadFiles(e.target.files)}/>
      <button onClick={()=>insertFile()}>Insertar</button>
    </>
  );
}

export default App;

And this is my view.py file that will process the information, for now, I just want to get the csv info in the frontend side, so the logic of how to process data doesn't matter right now.

@api_view(['POST'])
def eda(request):
    file = request.FILES['file']
    data = []
    with open(file, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)
        for rows in csvReader: 
            data.append(rows)
    
    response = {
        'csvData': data 
    }

    return Response(response)

CodePudding user response:

Seems like your files are not added in the FormData at all. It's because you are sending a list of files not a single file. So instead of this

 <input type="file" name="file" onChange={(e)=>uploadFiles(e.target.files)}/>

Use this

 <input type="file" name="file" onChange={(e)=>uploadFiles(e.target.files[0])}/>

and on Django side use this:

file = request.FILES.get('file') # won't raise exception
if file is None:
    # show some error response

CodePudding user response:

Instead of request.FILES.get('file') try using request.data.get('file')

  • Related