Django 管理中的多张图片上传

Multiple image upload in Django admin

我在尝试编写正确的模型以将多张图片上传到我的 Django 应用程序时遇到了很多麻烦。我希望能够通过 django 管理员上传这些图像。我试过使用 ImageField,但它一次只允许一张图片,我也希望能够调整图片大小。

这是我的 models.py:

class Lesson(models.Model):
    DRAFT = 'draft'
    PUBLISHED = 'published'

    CHOICES_STATUS = (
        (DRAFT, 'Draft'),
        (PUBLISHED, 'Published')
    )

    ARTICLE = 'article'
    QUIZ = 'quiz'

    CHOICES_LESSON_TYPE = (
        (ARTICLE, 'Article'),
        (QUIZ, 'Quiz')
    )

    course = models.ForeignKey(Course, related_name='lessons', on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    short_description = models.TextField(blank=True, null=True)
    long_description = models.TextField(blank=True, null=True)
    status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PUBLISHED)
    lesson_type = models.CharField(max_length=20, choices=CHOICES_LESSON_TYPE, default=ARTICLE)

Serializer.py:

class LessonListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Lesson
        fields = ('id', 'title', 'slug', 'short_description', 'long_description')

Admin.py:

class LessonAdmin(admin.ModelAdmin):
    list_display = ['title', 'course', 'status', 'lesson_type']
    list_filter = ['status', 'lesson_type']
    search_fields = ['title', 'short_description', 'long_description']
    inlines = [LessonCommentInline]

如果您想要多张图片,您需要为图片创建另一个 table(One2Many 关系)。

pip install --upgrade Pillow # 如果需要

# import PIL for image resizing
from PIL import Image

class Photo(models.Model):
    lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='photos')
    photo = models.ImageField(upload_to ='photos/')

    # resizing the image, you can change parameters like size and quality.
    def save(self, *args, **kwargs):
       super(Photo, self).save(*args, **kwargs)
       img = Image.open(self.photo.path)
       if img.height > 1125 or img.width > 1125:
           img.thumbnail((1125,1125))
       img.save(self.photo.path,quality=70,optimize=True)

对于管理员,您可以这样做:

admin.py
class PhotoAdmin(admin.StackedInline):
    model = Photo

class LessonAdmin(admin.ModelAdmin):
    inlines = [PhotoAdmin]

    class Meta:
        model = Lesson


admin.site.register(Photo)
admin.site.register(Lesson, LessonAdmin)