一、前言
本Part,将介绍Django-Xadmin的图片上传控件和文件上传控件的使用和效果。包括:
1、图片上传
2、文件上传
二、目录结构总览
1、本part,我们在这个结构下进行代码填充:
Project 目录 (Django-Xadmin学习项目)
|
|-- app
| `-- practise
...
三、图片上传控件要求安装pillow
1、如果Python环境没有安装pillow的情况下,写好上传控件运行项目会报如下错误:
ERRORS:
practise.Upload.upload_image: (fields.E210) Cannot use ImageField because Pillow is not installed.
HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow".
2、激活Python虚拟环境,安装Pillow
键入如下命令:
pip install Pillow
四、追加代码
1、在project/app/practise/models.py,追加代码:
class Upload(models.Model):
# 指定上传路径为项目load路径,其中%Y是取当前日期年,%m取当前日期月
UPLOAD_PATH_FILE = 'upload/file/%Y/%m'
UPLOAD_PATH_IMAGE = 'upload/image/%Y/%m'
title = models.CharField(max_length=10, verbose_name=u'标题')
upload_file = models.FileField(upload_to=UPLOAD_PATH_FILE, max_length=100, verbose_name=u'文件上传案例', null=True, blank=True,)
upload_image = models.ImageField(upload_to=UPLOAD_PATH_IMAGE, max_length=100, verbose_name=u'图片上传案例', null=True, blank=True,)
# 上传控件报错,ERRORS:
# practise.Upload.upload_image: (fields.E210) Cannot use ImageField because Pillow is not installed.
# HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow".
class Meta:
verbose_name = u'上传控件一览'
verbose_name_plural = verbose_name
2、在数据库生成新定义的表,Tools 工具栏运行 run manage.py Task输入:
makemigrations
migrate
3、数据库多了一张class对应的表
五、把这app注册到xadmin后台管理系统
1、在apps\practise\adminx.py文件追加:
from .models import Upload
class UploadAdmin(object):
list_display = ['title'] # 控制显示列数
search_fields = ['title'] # 控制搜索框的显示
list_filter = ['title'] # 控制筛选
xadmin.site.register(Upload, UploadAdmin)
六、查看效果
1、重启项目
2、查看效果