Programmatically upload files to Django

I checked a few other threads, but I still have a problem. I have a model that includes FileField, and I create semi-random instances for various purposes. However, I have a problem downloading files.

When I create a new file, it works (the new instance is saved in the database), the file is created in the corresponding directory, but the contents of the file are missing or damaged.

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() 

Thanks!

+7
django django-models django-file-upload
source share
1 answer

It can be as simple as opening a 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 it is open at the beginning of the file.

+18
source share

All Articles