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

浏览器显示

 

 

 

posted @ 2020-04-02 16:33  旅行没有终点  阅读(357)  评论(0编辑  收藏  举报