日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python图片重命名 工具_python - 请问django如何给上传的图片重命名

發布時間:2023/12/3 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python图片重命名 工具_python - 请问django如何给上传的图片重命名 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問 題

我的models.py:

pic = models.ImageField(upload_to='img/%Y/%m')

怎樣給上傳的圖片重命名?例如:以當前上傳的時間給圖片命名.謝謝~!

解決方案

結貼:

1、先在你項目中添加一個文件夾如:system 在文件夾下添加__init__.py 和storage.py文件,并在storage.py中添加如下代碼:

# -*- coding: UTF-8 -*-

from django.core.files.storage import FileSystemStorage

from django.http import HttpResponse

class ImageStorage(FileSystemStorage):

from django.conf import settings

def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL):

# 初始化

super(ImageStorage, self).__init__(location, base_url)

# 重寫 _save方法

def _save(self, name, content):

import os, time, random

# 文件擴展名

ext = os.path.splitext(name)[1]

# 文件目錄

d = os.path.dirname(name)

# 定義文件名,年月日時分秒隨機數

fn = time.strftime('%Y%m%d%H%M%S')

fn = fn + '_%d' % random.randint(0,100)

# 重寫合成文件名

name = os.path.join(d, fn + ext)

# 調用父類方法

return super(ImageStorage, self)._save(name, content)

2、在models.py文件中添加如下代碼:

from system.storage import ImageStorage

pic=models.ImageField(upload_to='img/%Y/%m/%d',storage=ImageStorage())

這樣就解決了問題,效果如下:

掃一掃關注IT屋

微信公眾號搜索 “ IT屋 ” ,選擇關注與百萬開發者在一起

總結

以上是生活随笔為你收集整理的python图片重命名 工具_python - 请问django如何给上传的图片重命名的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。