[Answered ]-How to save an in memory Excel file to a Django models.FileField

1👍

You need to convert the excel_file to a byte stream using io.BytesIO and pass that to the File constructor so the view should be:

def dataExtraction(request, pk):
    template = 'basic/form_data_extraction.html'
    plan = Plan.objects.get(pk=pk)
    context = {}

    form = DataExtractionForm(request.POST or None, request=request, plan=plan)

    if request.method == 'POST':
        if form.is_valid():
            cleaned_data = form.cleaned_data
            year = int(cleaned_data.get('year'))
            data_type = cleaned_data.get('data_type')
            data_from_list = cleaned_data.get('data_from_list')
            excel_file = extract_data(
                request,
                context,
                plan,
                year,
                data_type,
                data_from_list
            )
            today = datetime.date.today()
            file_name = "data_" + str(year) + ".xlsx"
            doc = DocuPlan(
                user=request.user,
                plan=plan,
                doc_type=DocuPlanType.DATA,
                date_order=plan.year_end(year),
                date_published=today,
                is_public=False,
                date_filed=today,
                file_name=file_name,
            )

            file_stream = io.BytesIO()
            excel_file.save(file_stream)
            file_stream.seek(0)
            file = File(file_stream, name=file_name)
            doc.document.save(file_name, file, save=True)


    context['form'] = form
    context['plan'] = plan
    return render(request, template, context=context)

Leave a comment