Django ImageField change file name on upload

前端 未结 5 1565
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 04:35

Upon saving me model \'Products\' I would like the uploaded image to be named the same as the pk for example 22.png or 34.gif I don\'t want to change the format of the image jus

5条回答
  •  抹茶落季
    2021-01-30 04:58

    You can pass a function into upload_to field:

    def f(instance, filename):
        ext = filename.split('.')[-1]
        if instance.pk:
            return '{}.{}'.format(instance.pk, ext)
        else:
            pass
            # do something if pk is not there yet
    

    My suggestions would be to return a random filename instead of {pk}.{ext}. As a bonus, it will be more secure.

    What happens is that Django will call this function to determine where the file should be uploaded to. That means that your function is responsible for returning the whole path of the file including the filename. Below is modified function where you can specify where to upload to and how to use it:

    import os
    from uuid import uuid4
    
    def path_and_rename(path):
        def wrapper(instance, filename):
            ext = filename.split('.')[-1]
            # get filename
            if instance.pk:
                filename = '{}.{}'.format(instance.pk, ext)
            else:
                # set filename as random string
                filename = '{}.{}'.format(uuid4().hex, ext)
            # return the whole path to the file
            return os.path.join(path, filename)
        return wrapper
    
    FileField(upload_to=path_and_rename('upload/here/'), ...)
    

提交回复
热议问题