I can't get my FileField's url set to what I want.
My model is defined by
class MyModel(models.Model):
pdf_file = models.FileField(upload_to="reports", null=True, blank=True)
# more stuff
and I create an instance using:
myModel = MyModel()
myModel.pdf_file = "some_file.pdf"
myModel.save()
myModel.pdf_file.url returns <MEDIA_URL>/some_file.pdf, while I would expect it to be <MEDIA_URL>/reports/some_file.pdf, because of the upload_to attribute.
What am I missing?
EDIT
I first tried to set a File object instead of a string but it duplicates my file with a _<duplication_num> appended to it, so I first create my file in a tmp folder, and delete it:
myModel.pdf_file = File(open(TMP_FILE_PATH + filename))
myModel.save()
# now that the file is saved to its final location, delete tmp
filepath = os.path.abspath(TMP_FILE_PATH + filename)
os.remove(filepath)
upload_to is used for uploading, You're assigning the string name directly. upload_to takes action only when you create a FileField object (by uploading from a form).
You can read the documentation here
upload_to is a directory relative to your project root where the files you upload are meant to be stored. But you are not assigning it a file, you are assigning it a string, which seems to be causing your FileField to assume you have a file named some_file.pdf in your MEDIA_ROOT.
Repeat: assigning a filename (string) makes FileField to ignore the path defined in upload_to and takes the given string as the real path.
Good luck :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With