Vishesh Mangla
Vishesh Mangla

Reputation: 753

Django feeding file data to a model

If you got a form that asks the user for a file upload and the file after some preprocessing gets a data dict which is fed to the model. How is the preprocessing step is to be done in this case? In the subclassed FormView's is_valid method one can do form.files to get the file obj, read it , preprocess it there and then feed the data to a model instance. But I think this would block the thread. What's the correct way?

Upvotes: 0

Views: 173

Answers (1)

Dunski
Dunski

Reputation: 672

From Django 3.1 onwards you could do something like this

import asyncio
from django.http import JsonResponse
from asgiref.sync import sync_to_async


@sync_to_async
def crunching_stuff(my_file):
    # do your file processing here
        
async def index(request):
    json_payload = {
        "message": "Your file is being processed"
    }
    my_file = request.POST.get('file')
    
    asyncio.create_task(crunching_stuff(my_file))
    return JsonResponse(json_payload)

Upvotes: 2

Related Questions