Wagtail 封装了理想的图片管理模块,大大减少了网站开发的工作量,在继续编写笔记之前,必须向 Wagtail 的开发者致敬!

绝大多数时候,网站项目都会超越 CMS 的范畴,如果能在普通的 DJango APP 上使用 Wagtial 的图片管理类,那一定是很感人的。

模型

在 Django 模型中,以外键的形式调用 wagtail Image 类。

from django import forms
from django.db import models
from wagtail.images.models import Image

class Product(models.Model):
    intro = models.CharField(
        '公司简介', null=True, blank=True, max_length=200)
    logo = models.ForeignKey(
        Image, on_delete=models.SET_NULL, null=True, blank=True, related_name='+')

视图

在视图里面定义上传图片到 Image 模型的方法。通常,网站会采用 ajax 处理文件上传,可以注释掉 get() 部分。

# 图片上传
from django.views import View
from wagtail.images import get_image_model
from wagtail.images.forms import get_image_form

from django.shortcuts import render, redirect, reverse
from django.http.response import HttpResponse

class ImageUpload(View):
    ImageModel = get_image_model()
    ImageForm = get_image_form(ImageModel)

    def get(self, request):
        form = self.ImageForm(user=request.user)
        return render(request, 'expo/upload.html', {'form': form})

    def post(self, request, *args, **kwargs):
        image = self.ImageModel(uploaded_by_user=request.user)
        form = self.ImageForm(request.POST, request.FILES,
                              instance=image, user=request.user)
        if form.is_valid():
            # Set image file size
            image.file_size = image.file.size

            # Set image file hash
            image.file.seek(0)
            image._set_file_hash(image.file.read())
            image.file.seek(0)

            form.save()

            return HttpResponse(image.id)
        else:
            return HttpResponse('图片上传错误!')

路由

from django.urls import path

from . import views

urlpatterns = [
    ...
    path('upload/', views.ImageUpload.as_view(), name='myapp.upload'),
]

Reference