1

I have written a code to upload an excel sheet and save the contents to mysql database. Below is the code to upload the file in memory.

form = UploadFileForm(request.POST,request.FILES)
if form.is_valid():
    file_in_memory = request.FILES['file'].read()
    wb = load_workbook(filename=BytesIO(file_in_memory), data_only=True)

Now, I want to upload a PDF file and save the path to mysql database using the same function. For instance, If excel has record A then there is an associated PDF file which I have to link. How do I handle this situation? Using formset is a solution? I am aware of multi-file upload but I assume that will save the file path to the database directly.

Sainath
  • 58
  • 1
  • 8

1 Answers1

0

I believe you can do this directly in a model.py using FileField.

from django.db import models
class UploadFile(models.Model):
    file_in_memory=models.FileField(upload_to='uploads/')
Matt Cremeens
  • 4,951
  • 7
  • 38
  • 67
  • Thanks, Matt for your response. But this will allow me to upload only one file correct? As of now, I am not saving the excel sheet to the disk. Just reading the contents.But I want to save PDF to the disk. – Sainath Aug 16 '18 at 11:29
  • You can upload as many as you want from a view. This model allows you to store any number of file records in your database using Django. – Matt Cremeens Aug 16 '18 at 13:18
  • So I am currently not using Models because I don't want the excel to be saved. It should read the content while in the memory. Therefore I have included this class in views.py `class UploadFileForm(forms.Form): file = forms.FileField()` This code will read the file in memory. `if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_in_memory = request.FILES['file'].read()` – Sainath Aug 16 '18 at 15:04