Django ImageField change file name on upload

前端 未结 5 1573
没有蜡笔的小新
没有蜡笔的小新 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:51

    By default Django keeps the original name of the uploaded file but more than likely you will want to rename it to something else (like the object's id). Luckily, with ImageField or FileField of Django forms, you can assign a callable function to the upload_to parameter to do the renaming. For example:

    from django.db import models
    from django.utils import timezone
    import os
    from uuid import uuid4
    
    def path_and_rename(instance, filename):
        upload_to = 'photos'
        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(upload_to, filename)
    

    and in models field:

    class CardInfo(models.Model):
        ...
        photo = models.ImageField(upload_to=path_and_rename, max_length=255, null=True, blank=True)
    

    In this example, every image that is uploaded will be rename to the CardInfo object's primary key which is id_number.

提交回复
热议问题