[Answered ]-Django FileField โ€“ how to save files to different directories

1๐Ÿ‘

Ok, so the way I do it is the following:

from django.db import models

def _upload_location(instance, filename):
    return f'{instance.owner.username}/{filename}'


class UploadFile(models.Model):
    file = models.FileField(upload_to=_upload_location)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

This way it stores the file inside of the folder you assigned in your settings.py as MEDIA_ROOT. Then puts it in a folder with the same name as your username. Afterwards follows the filename.

If the username as a foldername is a good choice is for sure debatable but you get the idea.

Find another good example here: FileField.upload_to

๐Ÿ‘คTarquinius

Leave a comment