python測試開發django-48.xadmin上傳圖片django-stdimage

前言

django經過自帶的ImageField能夠實現圖片上傳,若是想在列表頁面也顯示圖片縮略圖的話,能夠用django-stdimage插件來實現html

django-stdimage

django-stdimage的github文檔地址https://github.com/codingjoe/django-stdimagepython

實現如下功能的Django Field:git

  • Django-Storages兼容(S3)
  • 將圖像調整爲不一樣大小
  • 訪問模型級別的縮略圖,不須要模板標籤
  • 保留原始圖像
  • 異步渲染(Celery&Co)
  • 多線程和處理以得到最佳性能
  • 限制接受的圖像尺寸
  • 將文件重命名爲標準化名稱(使用可調用的upload_to)

環境準備,直接經過pip安裝,最新版本Version: 4.0.1github

pip install django-stdimagedjango

並加入'stdimage'到INSTALLED_APP在你的settings.py多線程

在settings.py配置上傳文件的目錄地址,參考前面一篇http://www.javashuo.com/article/p-csoltdka-ck.html異步

MEDIA_URL = '/media/'

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

官方案例

變量在字典中指定。鍵將是引用已調整大小的圖像的屬性。變量能夠定義爲元組或字典。性能

from django.db import models
from stdimage.models import StdImageField


class MyModel(models.Model):
    # works just like django's ImageField
    image = StdImageField(upload_to='path/to/img')

    # creates a thumbnail resized to maximum size to fit a 100x75 area
    image = StdImageField(upload_to='path/to/img',
                          variations={'thumbnail': {'width': 100, 'height': 75}})

    # is the same as dictionary-style call
    image = StdImageField(upload_to='path/to/img', variations={'thumbnail': (100, 75)})

    # creates a thumbnail resized to 100x100 croping if necessary
    image = StdImageField(upload_to='path/to/img', variations={
        'thumbnail': {"width": 100, "height": 100, "crop": True}
    })

    ## Full ammo here. Please note all the definitions below are equal
    image = StdImageField(upload_to='path/to/img', blank=True, variations={
        'large': (600, 400),
        'thumbnail': (100, 100, True),
        'medium': (300, 200),
    })

用於在模板中使用生成的變量myimagefield.variation_name。如url

<a href="{{ object.myimage.url }}"><img alt="" src="{{ object.myimage.thumbnail.url }}"/></a>

實踐案例

經過上面的案例介紹,接下來寫個實際的案例練習下插件

# models.py

from django.db import models
from django.utils import timezone
from datetime import datetime
from stdimage.models import StdImageField

# Create your models here.


class UploadImage(models.Model):
    '''上傳圖片功能'''
    name = models.CharField(max_length=30, verbose_name="名稱", default="")   # 標題
    image = StdImageField(max_length=100,
                          upload_to='path/to',
                          verbose_name=u"傳圖片",
                          variations={'thumbnail': {'width': 100, 'height': 75}})
    # 時間可編輯
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加時間")


    def url(self):
        if self.image:
            return self.image.url
        else:
            return "url爲空"

    def image_img(self):
        if self.image:
            href = self.image.url    # 點擊後顯示的放大圖片
            src = self.image.thumbnail.url    # 頁面顯示的縮略圖
            # 插入html代碼
            image_html = '<a href="%s" target="_blank" title="傳圖片"><img alt="" src="%s"/>'%(href, src)
            return image_html
        else:
            return '上傳圖片'

    image_img.short_description = '圖片'
    image_img.allow_tags = True     # 列表頁顯示圖片

    class Meta:
        verbose_name = "傳圖片"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

adminx.py註冊表信息

# adminx.py
import xadmin
from xadmin import views
from .models import  UploadImage


class ControlImage(object):
    # 顯示不要用image,而應該用image_img
    list_display = ['name', 'image_img', 'url', 'add_time']

xadmin.site.register(UploadImage, ControlImage)

urls.py配置圖片的URL地址訪問,要否則查詢詳情的時候縮略圖沒法正常顯示

from . import settings
from django.views.static import serve

urlpatterns = [

    url(r'^media/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}),

]

配置好以後,執行 makemigrations 和migrate,同步數據

python manage.py makemigrations
python manage.py migrate

xadmin後臺顯示

列表顯示縮略圖,點擊能夠放大

關於allow_tags的用法能夠看下一篇http://www.javashuo.com/article/p-xpqrwvoh-q.html

相關文章
相關標籤/搜索