Django - FileField - PDF vs octet-stream - AWS S3
I have a model with a file field like so:
class Document(models.Model):
file = models.FileField(...)
Elsewhere in my application, I am trying to download a pdf file from an external url and upload it to the file field:
import requests
from django.core.files.base import ContentFile
...
# get the external file:
response = requests.get('<external-url>')
# convert to ContentFile:
file = ContentFile(response.content, name='document.pdf')
# update document:
document.file.save('document.pdf', content=file, save=True)
However, I have noticed the following behavior:
- files uploaded via the django-admin portal have the
content_type"application/json" - files uploaded via the script abobe have the
content_type"application/octet-stream"
How can I ensure that files uploaded via the script have the "application/json" content_type? Is it possible to set the content_type on the the ContentFile object? This is important for the frontend.
Other notes:
- I am using AWS S3 as my file storage system.
- Uploading a file from my local file storage via the scirpt (i.e. using
with open(...) as file:still uploads a file as "applicaton/octet-stream"
The solution, get this, is to simply add a content_type attribute to the ContentFile instance:
import requests
from django.core.files.base import ContentFile
...
# get the external file:
response = requests.get('<external-url>')
# convert to ContentFile:
file = ContentFile(response.content, name='document.pdf')
file.content_type = "application/pdf" # <-- this
# update document:
document.file.save('document.pdf', content=file, save=True)