There are two fields in Django that take upload_to
parameter. With this parameter, you can define to which folder your files will be persisted.
There are different ways of saving a file to disk. I’m talking about the naming of the files.
You may want to save the files under the name they were uploaded. Here, for example, I just want to put them inside brand_logos
folder in my server, I don’t want to change the names of the incoming images.
from djongo.storage import GridFSStorage grid_fs_storage = GridFSStorage(collection='myfiles') class Brand(models.Model): name = models.CharField( max_length=128, blank=False, null=False, unique=True ) logo = models.ImageField(upload_to="brand_logos", blank=True, null=True)
Moreover, ables could be partitioned so that each sub-directory of a path was mapped to specific data values. For example, each day’s worth of data for a given table would be in a single sub-directory. Then you need to write a specific function like the below. This function categorizes each day’s file by date inside the myfiles
folder.
def upload_to(instance, filename): date = datetime.now().strftime('%Y%m%d') filename = "myfiles" + "/" + date + "/" + filename return filename class Brand(models.Model): name = models.CharField( max_length=128, blank=False, null=False, unique=True ) logo = models.ImageField(upload_to=upload_to, blank=True, null=True)
See you in the next article 🙂