django实现文件(图片)上传之后自动修改名称以及页面上传图片时的各种提醒:
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) def _save(self,name,content): #重新文件上传 import os,time,hashlib #获取文件后缀 ext = os.path.splitext(name)[1] #文件目录 d = os.path.dirname(name) #定义文件夹名称 fn = hashlib.md5(time.strftime(‘%Y%m%d%H%M%S‘).encode(‘utf-8‘)).hexdigest() name = os.path.join(d,fn+ext) #调用父类方法 return super(ImageStorage,self)._save(name,content)
2、在models.py文件中添加如下代码:
from django.db import models from datetime import datetime from system.stroage import ImageStorage # Create your models here. #文章咨询表 class Article(models.Model): title = models.CharField(max_length=250, null=False, verbose_name=‘标题‘, unique=True) content = models.TextField(verbose_name=‘内容‘) add_time = models.DateTimeField(verbose_name=‘添加时间‘, default=datetime.now) update_time = models.DateTimeField(verbose_name=‘修改时间‘, null=True) state = models.IntegerField(verbose_name=‘状态‘, default=1) cat_id = models.ForeignKey(Category, on_delete=models.CASCADE) t = datetime.now() cover_map = models.ImageField(verbose_name=‘缩列图‘,upload_to=‘article/%Y/%m/%d‘,default=‘1.png‘,storage=ImageStorage()) class Meta: verbose_name = ‘文章‘ ordering = [‘-add_time‘] def __str__(self): return self.title def delete(self, using=None, keep_parents=False): print(1111)
原文地址:https://www.cnblogs.com/sunshenggang/p/9572856.html
时间: 2024-10-12 16:00:02