Django: How to save original filename in FileField?

前端 未结 3 1971
攒了一身酷
攒了一身酷 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 02:01

    The posted code normally works, perhaps the actual code is

    class FooModel(models.Model):
        filename = models.CharField(max_length=128)
        file = models.FileField(upload_to=get_random_filename)
    

    Note the switching of the ordering of the fields above.

    This won't work because: the upload_to() is invoked by the pre_save(), here in the code, when the actual value of the FileField is required. You could find that the assignment to the attribute filename in the upload() is after the generating of the first param filename in the inserting sql. Thus, the assignment does not take effect in the generated SQL and only affects the instance itself.

    If that's not the issue, please post the code you typed in shell.

提交回复
热议问题