Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23218

Save file (not in MEDIA_ROOT) to Django FileField from fastapi UploadFile

$
0
0

I need to save a fastapi UploadFile object directly to a Django model defined below:

class MyFile(models):    file = models.FileField(upload_to="files/")

In the API, I managed to obtain file object from the SpooledTemporaryFile using the read and write methods like in the block below:

async def file_upload(file: UploadFile = File(...)):    async with aiofiles.open(f"path/{file.filename}", "wb") as media:        cont = await file.read()        await media.write(cont)

Then I try to convert the new file to FieldFile type in Django to be able to save it in the MyFile.file field but it kept returning a TypeError with the description: write() argument must be str, not generator

from django.core.files import File as DjangoFileasync def file_upload(file: UploadFile = File(...)):    ...    async with aiofiles.open(f"path/{file.filename}") as media:        d_file = DjangoFile(media)        file_model = MyFile()        file_model.file.save(file.filename, d_file)        file_model.save()    return {"ok": True}

The stack trace revealed file_model.file.save(file.filename, d_file) as the offending line.

>>> type(file.filename)str>>> type(d_file)<class 'django.core.files.base.File'>

Could you point me in the right direction?


Viewing all articles
Browse latest Browse all 23218

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>