django admin上传图片文件到七牛云
forms定义
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "leo"
__time__ = "2023-01-20"
from django.db.models import FileField
from utils.qiniu_utils import upload_img_to_qiniu
"""
在数据库是CharFiled,但是想在页面上渲染成文件上传框
https://blog.csdn.net/qq_52385631/article/details/123308894
"""
from django import forms
from sale.models import PurchaseOrderItem
class PurchaseOrderItemModelForm(forms.ModelForm):
img = forms.FileField()
class Meta:
model = PurchaseOrderItem
fields = '__all__'
widgets = {
'img': forms.FileInput()
}
# 自定义上传 return 路径
def clean_img(self):
# 上传文件到七牛云
file = self.cleaned_data['img']
return upload_img_to_qiniu(file)
写个工具类
import base64
import os
from qiniu import Auth, put_file, etag, put_data
import qiniu.config
from utils.time_utils import get_custom_today
from xl import settings
# 构建鉴权对象
q = Auth(settings.qiniu_access_key, settings.qiniu_secret_key)
# 要上传的空间
bucket_name = settings.qiniu_bucket_name
def upload_img_to_qiniu(file):
"""
上传图片文件到七牛云
:param file:
:return:
"""
# 上传后保存的文件名 '2023/01/20/logo.png'
key = get_custom_today() + '/' + file.name
# 生成上传 Token,可以指定过期时间等
token = q.upload_token(bucket_name, key, 3600)
ret, info = put_data(token, key, file)
return settings.qiniu_url_refix + key
if __name__ == '__main__':
# 上传后保存的文件名
key = '2023/20/logo.png'
# 生成上传 Token,可以指定过期时间等
token = q.upload_token(bucket_name, key, 3600)
# 要上传文件的本地路径
localfile = '/Users/leo/Documents/Workspace/Python/xl/bbb.jpg'
ret, info = put_file(token, key, localfile, version='v2')
print(info)
使用forms
class PurchaseOrderItemInline(admin.TabularInline):
form = PurchaseOrderItemModelForm
model = PurchaseOrderItem