15

I have checked several other threads but I am still having a problem. I have a model that includes a FileField and I am generating semi-random instances for various purposes. However, I am having a problem uploading the files.

When I create a new file, it appears to work (the new instance is saved to the database), a file is created in the appropriate directory, but the file's content is missing or corrupt.

Here is the relevant code:

class UploadedFile(models.Model):
  document = models.FileField(upload_to=PATH)


from django.core.files import File

doc = UploadedFile()
with open(filepath, 'wb+') as doc_file:
   doc.documen.save(filename, File(doc_file), save=True)
doc.save()

Thank you!

2 Answers 2

28

Could it be as simple as the opening of the file. Since you opened the file in 'wb+' (write, binary, append) the handle is at the end of the file. try:

class UploadedFile(models.Model):
  document = models.FileField(upload_to=PATH)


from django.core.files import File

doc = UploadedFile()
with open(filepath, 'rb') as doc_file:
   doc.document.save(filename, File(doc_file), save=True)
doc.save()

Now its open at the beginning of the file.

Sign up to request clarification or add additional context in comments.

3 Comments

why do you save a whole model? isn't it redundant (called earlier by doc.document.save() with save=True)
I have actually had a similar problem and adding the 'b' flag solved the problem - I was opening pdf files.
What is filename ?
2

For pdf files I used the receipt from django doc: https://docs.djangoproject.com/en/4.2/topics/files/

from pathlib import Path

from django.core.files import File

class Invoice(TimeStampedModel):
    magnifinance_file = models.FileField(blank=True, null=True)

invoice = Invoice.objects.get(pk=1)
path = Path('/path_to_file/mf_invoice.pdf')
with path.open(mode="rb") as f:
     invoice.magnifinance_file = File(f, name=path.name)
     invoice.save()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.