Django: How to save original filename in FileField?

前端 未结 3 1970
攒了一身酷
攒了一身酷 2021-01-02 01:33

I want the filenames to be random and therefore I use upload_to function which returns a random filename like so:

from uuid import uuid4
import          


        
3条回答
  •  盖世英雄少女心
    2021-01-02 01:46

    You could go the route of populating the filename during the save process. Obviously you'll have to store the original file name in memory when your get_random_filename runs.

    # inside the model
    class FooModel(models.Model):
        file = models.FileField(upload_to=get_random_filename)
        filename = models.CharField(max_length=128)
    
        def save(self, force_insert=False, force_update=False):
            super(FooModel, self).save(force_insert, force_update)
                #Do your code here...
    

提交回复
热议问题