Prateek Jain
Prateek Jain

Reputation: 196

How to take a file as a form-field input without defining it as a Model in Django?

I have written a simple API for Tax Analysis through a ZIP file sent by our supplier using the FastAPI framework. (As you can see below). However, I had to start shifting my APIs to Django for some technical reasons. I have been searching for a way to input a file as form-data in Django, but all of them require a Model to be created for that, however, for my requirement, I don't need that file stored anywhere permanently, just temporarily in the memory for further analysis. Below is an example of how I was taking the file as an input through FastAPI.

@app.get('/xtracap_gst/files')
async def gst(file: UploadFile = File(any))

Any inputs would be appreciated

EDIT:

I have managed to get the file uploaded in my memory but it returns a MultiValueDictionary and as per documentation, it is further handled by the UploadedFile Class of request.FILES. However, on running UploadedFile.read() it says TypeError: 'property' object is not callable . Please find my code below:

@api_view (['GET','POST'])
def gstAnalysis(request):
    if request.method == 'POST':
        parser_classes = (FileUploadParser,)
        file = request.FILES
        file =  UploadedFile.read()
        print(file)
        return Response({'test'})
    else:
        return Response({'Test'}) 

Upvotes: 0

Views: 99

Answers (1)

furas
furas

Reputation: 142641

I can't test it but ...

you should get dictionary request.FILES (even if you send one file) and every element in dictionary is a object UploadedFile and its key is name from <input name=...>. And UploadedFile has method .read()

  for name, uploaded_file in request.FILES.items(): 
      print( name )    
      print( uploaded_file.read() ) 

Upvotes: 1

Related Questions