• python测试开发django-47.xadmin上传图片和文件


    前言

    xadmin上传图片和上传文件功能

    依赖环境

    如果没安装Pillow的话,会有报错: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".

    需先安装Pillow环境

    pip install Pillow

    models模块设计

    先设计一个model,用ImageField存放图片,FileField放文件,upload_to参数是存放的目录

    # models.py
    
    from django.db import models
    from django.utils import timezone
    
    # Create your models here.
    
    
    class FileImage(models.Model):
        '''上传文件和图片'''
        title = models.CharField(max_length=30, verbose_name="名称", default="")   # 标题
        image = models.ImageField(verbose_name="上传图片", upload_to="up_image", blank=True)
        fiels = models.FileField(verbose_name="上传文件", upload_to="up_file", blank=True)
        add_time = models.DateField(auto_now=True, verbose_name="添加时间")
        
    
        def __str__(self):
            return self.__doc__ + "title->" + self.title
    
        class Meta:
            verbose_name = "上传文件和图片"
            verbose_name_plural = verbose_name
    

    adminx.py文件注册表信息

    # adminx.py
    import xadmin
    from xadmin import views
    from .models import  FileImage
    
    class ControlFiles(object):
        list_display = ['title', "add_time"]
    
    
    xadmin.site.register(FileImage, ControlFiles)
    

    urls.py配置图片的URL地址访问,要不然查询详情的时候缩略图无法正常显示

    from . import settings
    from django.views.static import serve
    
    urlpatterns = [
    
        url(r'^media/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}),
    
    ]
    

    settings.py配置

    在settings.py配置上传文件的目录地址

    MEDIA_URL = '/media/'
    
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    

    配置好之后,执行 makemigrations 和migrate,同步数据

    python manage.py makemigrations
    python manage.py migrate

    在xadmin上传图片后,会自动生成media目录

    xadmin后台页面

    新增上传图片页面

    上传完成后查询详情页面

  • 相关阅读:
    12.Scala- 注解
    11.Scala-特质
    10.Scala-继承
    9.Scala- 包和引入
    8.Scala-对象
    7.Scala-类
    6.Scala-高阶函数
    5.Scala-匹配模式
    4.Scala-数据结构
    Ruby on Rails Tutorial 第四章 Rails背后的Ruby 之 类
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/10653878.html
Copyright © 2020-2023  润新知