Django admin background management system uploads and adds pictures and saves them in Alibaba Cloud oss

Table of contents

1. Configure admin to upload pictures to Alibaba Cloud oss

2. Configure the picture uploaded to Alibaba Cloud oss ​​by the admin background as a custom name


Description of the problem: When developing your own application/webpage front and backend, you can call the interface of Alibaba Cloud oss ​​to upload pictures to oss for saving and reading, which is very convenient. But in the admin background that comes with django, how to configure the added pictures to be uploaded to Alibaba Cloud oss ​​for storage?

1. Configure admin to upload pictures to Alibaba Cloud oss

1, models model

class Product(models.Model):
    """常规商品"""
    name = models.CharField(verbose_name="商品名称", max_length=50)
    desc = models.TextField(verbose_name="描述")
    show_img = models.ImageField(verbose_name="展示图", upload_to='images/')
    detail_img = models.ImageField(verbose_name="详情图", upload_to='images/')

    is_sale = models.BooleanField(verbose_name="是否上架", default=False)  # 为False时是下架
    is_show = models.BooleanField(verbose_name="是否展示在首页", default=True)  # 为True时是展示在首页
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    update_time = models.DateTimeField(auto_now=True, verbose_name="最后一次修改时间")


    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "常规商品"
        verbose_name_plural = verbose_name

2. Configure media to support image upload

settings.py

# settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

project root urls.py

# urls.py 添加media配置
from django.views.static import serve
from django.urls import path, include, re_path


urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('users.urls')),
    path('goods/', include('goods.urls')),
    # 新增media配置
    re_path(r'^media/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}),
]

3. Install the required modules

Install django-aliyun-oss2-storage, refer to the configuration on github  to install django-aliyun-oss2-storage

pip install -i https://pypi.douban.com/simple django-aliyun-oss2-storage

 If the pip installation is unsuccessful, you can download the source code from github, unzip it and go to the directory where setup.py is located, and use the python setup.py install command to install it (errors may be reported during the process, and the source code can be successfully installed by modifying the source code according to the error message)

 4. Related configuration in settings.py

# admin后台上传图片到oss
DEFAULT_FILE_STORAGE = 'aliyun_oss2_storage.backends.AliyunMediaStorage'  # 默认admin 上传oss配置
ACCESS_KEY_ID = "40ZhE1HyuWdllpMh"
ACCESS_KEY_SECRET = "KbxtlKSvKyuyuymTiQvrxhsYFMguXy"
END_POINT = "oss-us-west-1.aliyuncs.com"
BUCKET_NAME = "XXXX"
ALIYUN_OSS_CNAME = "" # 自定义域名,如果不需要可以不填写
BUCKET_ACL_TYPE = "private" # private, public-read, public-read-write
# private:仅创建者可以访问对象,默认值。
# public-read:所有人都可以读取对象,但只有创建者可以写入。
# public-read-write:所有人都可以读取和写入对象,不推荐使用。
# authenticated-read:所有 AWS 用户都可以读取对象,但只有创建者可以写入。
# aws-exec-read:Amazon EC2 实例可以读取对象,但只有创建者可以写入。
# bucket-owner-read:存储桶所有者可以读取对象,但其他人不行。
# bucket-owner-full-control:存储桶所有者可以读取和写入对象,其他人不行。

At this point, when you add pictures in the admin background again and save them, they can be automatically uploaded to Alibaba Cloud oss

2. Configure the picture uploaded to Alibaba Cloud oss ​​by the admin background as a custom name

Problem: When the admin background uploads pictures and saves them to oss, it will directly use the uploaded picture name, which will cause the previously uploaded file with the same name to be replaced when there is a file with the same name uploaded. This is not the result we want, so yes It is particularly important to automatically generate non-repetitive names for uploaded pictures!

1. Override the default method

import os
from aliyun_oss2_storage.backends import AliyunMediaStorage


class AdminMediaStorage(AliyunMediaStorage):
    """重写AliyunMediaStorage自定义admin后台上传到阿里云oss的图片名称"""

    def get_available_name(self, name, max_length=None):
        # 生成admin后台自定义的图片名称
        ext = name.split('.')[-1]
        filename = '{}.{}'.format(uuid.uuid4().hex, ext)
        return super().get_available_name(filename, max_length), name

    def _save(self, name, content):
        # 获取存储路径并保存到阿里云OSS

        path = os.path.split(name[1])
        if getattr(content, 'content_type', None) is None:
            content_type = mimetypes.guess_type(name)[0]
            content.content_type = content_type
        return super()._save(path[0] + '/' + name[0], content)

 Note: The _save method I rewritten here finally calls the superclass _save method. The first parameter is spliced ​​​​to save the file path in Alibaba Cloud oss, such as user/image/head_img.png

2. Modify the original configuration in settings.py

original configuration

DEFAULT_FILE_STORAGE = 'aliyun_oss2_storage.backends.AliyunMediaStorage'

 replace with

DEFAULT_FILE_STORAGE = 'goods.admin.AdminMediaStorage'  # 自定义admin 上传oss配置

Guess you like

Origin blog.csdn.net/qq_37140721/article/details/130801276