[Django]-How to Create and Save File in Django Model

5👍

It seems like your view is quite close to doing what you want. In your model, add a FileField for order_file:

class Orders(models.Model):

    ...
    order_file = models.FileField(upload_to='path/to/storage/', null=True, blank=True)

Then in your view, save the BytesIO object you’ve created to the order_file field in the Orders object with the correct reference_id by wrapping it in a File object:

from django.core.files import File

def docjawn(request):

    reference = request.POST.get('Reference_IDs')
    manifest = Manifests.objects.all().filter(reference__reference=reference)
    order = Orders.objects.get(reference=reference)

    # Generate doc file
    ...

    doc_io = io.BytesIO()
    doc.save(doc_io)
    doc_io.seek(0)

    # Save the BytesIO to the field here
    order.order_file.save("generated_doc.docx", File(doc_io))

    response = HttpResponse(doc_io.read())
    response["Content-Disposition"] = "attachment; filename=generated_doc.docx"
    response["Content-Type"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"

    return response

Leave a comment