Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Upload Files in Django

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!

like image 470
SapphireSun Avatar asked Jan 03 '10 03:01

SapphireSun


1 Answers

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.

like image 172
JudoWill Avatar answered Oct 22 '22 06:10

JudoWill