[Django] Custom storage backend returns the URL link of the complete picture

When we store pictures in Django, we do not store pictures directly, but store the unique identifier of the picture, and then obtain the picture through the identifier. For example, the following model class has an image field, and the field type is ImageField

class SKUImage(BaseModel):
    sku = models.ForeignKey(SKU, on_delete=models.CASCADE, verbose_name='sku')
    image = models.ImageField(verbose_name='图片')  # 存储图片

    class Meta:
        db_table = 'tb_sku_image'

    def __str__(self):
        return '%s %s' % (self.sku.name, self.id)

The ImageField type has a url attribute, which returns the URL link of the image (that is, the unique identifier). The current
Insert picture description here
im.image.url is just the original image identifier. What we want is a complete URL link with a domain name. , So we need to customize the storage backend and rewrite the url() function to return the complete image link

1. Custom storage backend

Create a new py file, such as fastdfs.py,
create a new class, inherit Storage, and rewrite the url() method, splicing the name parameter of the method with a custom string and then return

from django.core.files.storage import Storage

class FastDFSStorage(Storage):
    def _open(self,name,mode='rb'):
        # 打开django本地文件
        pass
    def _save(self,name,content,max_length=None):
        # 上传图片
        pass
    # 给返回的图片标识加上前缀
    def url(self, name):
        return "http://image.mysite.site:8888/" + name

2. Modify the configuration file

Modify the configuration file to tell Django to use our custom storage backend

# 指定自定义的Django文件存储类
DEFAULT_FILE_STORAGE = 'xxxxxx.utils.fastdfs.FastDFSStorage' 

Other similar operations

[Django] Customized authentication backend ModelBackend completes multi-mobile phone number mailbox login

[Django] Create a user, inherit the AbstractUser custom user model class

Guess you like

Origin blog.csdn.net/qq_39147299/article/details/108538974