python測試開發django-44.xadmin上傳圖片和文件

前言

xadmin上傳圖片和上傳文件功能python

依賴環境

若是沒安裝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".django

需先安裝Pillow環境url

pip install Pillowspa

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文件註冊表信息code

# 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地址訪問,要否則查詢詳情的時候縮略圖沒法正常顯示blog

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,同步數據ip

python manage.py makemigrations
python manage.py migrateget

在xadmin上傳圖片後,會自動生成media目錄

xadmin後臺頁面

新增上傳圖片頁面

上傳完成後查詢詳情頁面

相關文章
相關標籤/搜索