Django xadmin image upload and thumbnail processing

Basic summary

When developing with python django, I choose the Xadmin background management system framework, because it * has rich built-in functions, not only providing basic CRUD functions, but also built-in rich plug-in functions. Including data export, bookmark, chart, data add wizard, photo album and other expansion functions. But when uploading pictures to rename picture files and generate picture preview pictures, I found some code written by Daniel from the Internet, and there was an error in my project, so I groped for Django stdimage( Refer to official documents )The solution to generate preview image + rename image is as follows:

  • step 1. Installation

pip install django-stdimage==3.2.0 -i "https://pypi.doubanio.com/simple/"
  • step 2. Configure settings.py

 

step 3. Configure models.py

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'stdimage',  #Remember to add entry

] 
  • step 3. Configure models.py

from datetime import datetime
from stdimage.models import StdImageField
from stdimage.utils import UploadToUUID

class Banner(models.Model):
    title = models.CharField(max_length=100, verbose_name=u"Title")
    image = StdImageField(max_length=100,                      
    upload_to=UploadToUUID(path=datetime.now().strftime('banner/%Y/%m')),
                          verbose_name=u"Rotation chart",
                          variations={'thumbnail': {'width': 100, 'height': 75}})
    url = models.CharField(max_length=100, verbose_name=u"Access address")
    index = models.IntegerField(default=100, verbose_name=u"order")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"Adding time")

    class Meta:
        verbose_name = u"Rotation chart"
        verbose_name_plural = verbose_name

    def image_img(self):
        if self.image:
            return str('<img src="%s" />' % self.image.thumbnail.url)
        else:
            return u'Upload pictures'

    image_img.short_description = 'Rotation chart'
    image_img.allow_tags = True

    def __str__(self):
        return '{0}(In the first place{1}position)'.format(self.title, self.index) 
  • step 4. Configure adminx.py

class BannerAdmin(object):
    #Display should use image instead of image
    list_display = ['title', 'image_img', 'url', 'index', 'add_time']
    search_fields = ['title', 'url', 'index']
    list_filter = ['title',  'url', 'index', 'add_time']
#Sign up for a carousel
xadmin.site.register(Banner, BannerAdmin)
  • step 5. Configure urls.py

from django.urls import path, re_path
from django.views.static import serve
import xadmin
from Aiword.settings import MEDIA_ROOT

urlpatterns = [
    path('xadmin/', xadmin.site.urls),

    # Handle the url of image display, use Django's own serve,
    # The input parameter tells it which path to look for. We have the configured path MEDIAROOT
    re_path('media/(?P<path>.*)', serve, {"document_root": MEDIA_ROOT}),
]
  • Effect picture:

 
Rendering 1
 
Rendering II

Official document description:

By default, StdImageField stores images without modifying the filename.
If you want to use a more consistent filename, you can use the built-in upload call
For example:

from stdimage.utils import UploadToUUID, UploadToClassNameDir, \
UploadToAutoSlug,UploadToAutoSlugClassNameDir


class MyClass(models.Model):
    title = models.CharField(max_length=50)    

    # File saved to MEDIA_ROOT/myclass/#FILENAME#.#EXT#
    image1 = StdImageField(upload_to=UploadToClassNameDir())    

    # The file name is customized and saved to MEDIA_ROOT/myclass/pic.#EXT#
    image2 = StdImageField(upload_to=UploadToClassNameDir(name='pic'))    

    # Filename Auto uuid Rename upload to-> MEDIA_ROOT/images/#UUID#.#EXT#
    image3 = StdImageField(upload_to=UploadToUUID(path='images'))    

    # Document basis uuid Rules for file rename and upload to MEDIA_ROOT/myclass/#UUID#.#EXT#
    image4 = StdImageField(upload_to=UploadToClassNameDirUUID())    

    # File saved to MEDIA_ROOT/images/#SLUG#.#EXT#
    image5 = StdImageField(upload_to=UploadToAutoSlug(populate_from='title'))    
   
    # File saved to MEDIA_ROOT/myclass/#SLUG#.#EXT#
   image6 =StdImageField(
          upload_to=UploadToAutoSlugClassNameDir(populate_from='title'))

  


Link: https://www.jianshu.com/p/c726620280113

Tags: Python Django pip

Posted on Wed, 08 Jan 2020 07:04:20 -0800 by SwiftlyTilting