Enforce unique upload file names using django?

后端 未结 7 2082
别跟我提以往
别跟我提以往 2020-11-28 23:03

What\'s the best way to rename photos with a unique filename on the server as they are uploaded, using django? I want to make sure each name is used only once. Are there any

7条回答
  •  时光取名叫无心
    2020-11-28 23:33

    A better way could be using a common class in your helpers.py. This way you could reuse the random file generator across your apps.

    In your helpers.py:

    import os
    import uuid
    from django.utils.deconstruct import deconstructible
    
    
    @deconstructible
    class RandomFileName(object):
        def __init__(self, path):
            self.path = os.path.join(path, "%s%s")
    
        def __call__(self, _, filename):
            # @note It's up to the validators to check if it's the correct file type in name or if one even exist.
            extension = os.path.splitext(filename)[1]
            return self.path % (uuid.uuid4(), extension)
    

    And then in your model just import the helper class:

    from mymodule.helpers import RandomFileName 
    

    And then use it:

    logo = models.ImageField(upload_to=RandomFileName('logos'))
    

    Ref: https://coderwall.com/p/hfgoiw/give-imagefield-uploads-a-unique-name-to-avoid-file-overwrites

提交回复
热议问题