Django测试开发-35- xadmin模板中添加上传文件和图片功能
一、依赖环境
pip3 install Pillow
二、具体实现
models.py
class FileImage(models.Model): """ 上传文件和图片 """ title = models.CharField(max_length=30,verbose_name="标题",default="") image = models.ImageField(verbose_name="上传图片",upload_to="up_image",blank=True) files = models.FileField(verbose_name="上传文件",upload_to="up_file",blank=True) update_time = models.DateField(auto_now=True,verbose_name="更新时间") create_time = models.DateTimeField(auto_now_add=True,verbose_name="添加时间") def __str__(self): return self.title class Meta: verbose_name = "上传文件和图片" verbose_name_plural = verbose_name
adminx.py
class ControlFileImage(object): list_display = ['title','create_time'] xadmin.site.register(FileImage,ControlFileImage)
MyDjango.urls.py配置图片的URL地址访问,要不然查询详情的时候缩略图无法正常显示
from django.conf.urls import url from . import settings from django.views.static import serve urlpatterns = [ url(r'^media/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}), ]
settings.py
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media')
执行数据库生成和同步
python3 manage.py makemigrations
python3 manage.py migrate
浏览器显示
当有些人一出生就有的东西,我们要为之奋斗几十年才拥有。但有一样东西,你一辈子都不会有,那就是我们曾经一无所有。