사용자 지정 이미지 모델

Image 모델은 사용자 지정할 수 있으며, 이미지에 추가 필드를 추가할 수 있습니다.

이를 위해 프로젝트에 두 가지 모델을 추가해야 합니다.

  • wagtail.images.models.AbstractImage 를 상속하는 이미지 모델 자체. 여기에 추가 필드를 추가합니다.

  • wagtail.images.models.AbstractRendition 을 상속하는 렌디션 모델. 새 모델의 렌디션을 저장하는 데 사용됩니다.

다음은 예시입니다.

# models.py
from django.db import models

from wagtail.images.models import Image, AbstractImage, AbstractRendition


class CustomImage(AbstractImage):
    # 여기에 이미지에 추가 필드를 추가합니다.

    # 캡션 필드를 추가하려면:
    # caption = models.CharField(max_length=255, blank=True)

    admin_form_fields = Image.admin_form_fields + (
        # 그런 다음 여기에 필드 이름을 추가하여 폼에 표시되도록 합니다.
        # 'caption',
    )

    @property
    def default_alt_text(self):
        # 설명이 비어 있는 경우 편집자가 특정 대체 텍스트를 추가하도록 강제합니다.
        # 일반적으로 파일 이름에서 파생되는 이미지 제목을 사용하지 마십시오.
        return getattr(self, "description", None)

class CustomRendition(AbstractRendition):
    image = models.ForeignKey(CustomImage, on_delete=models.CASCADE, related_name='renditions')

    class Meta:
       constraints = [
            models.UniqueConstraint(
                fields=("image", "filter_spec", "focal_point_key"),
                name="unique_rendition",
            )
        ]

그런 다음 WAGTAILIMAGES_IMAGE_MODEL 설정을 이 모델을 가리키도록 설정합니다.

WAGTAILIMAGES_IMAGE_MODEL = 'images.CustomImage'

내장 이미지 모델에서 마이그레이션

기존 사이트에서 사용자 지정 이미지 모델을 사용하도록 변경할 때, 이미지는 새 모델로 자동으로 복사되지 않습니다. 이전 이미지를 새 모델로 복사하려면 데이터 마이그레이션 을 사용하여 수동으로 수행해야 합니다.

내장 이미지 모델을 참조하는 모든 템플릿은 이전과 같이 계속 작동하지만, 새 이미지를 보려면 업데이트해야 합니다.

이미지 모델 참조

wagtail.images.get_image_model()

Get the image model from the WAGTAILIMAGES_IMAGE_MODEL setting. Useful for developers making Wagtail plugins that need the image model. Defaults to the standard wagtail.images.models.Image model if no custom model is defined.

wagtail.images.get_image_model_string()

Get the dotted app.Model name for the image model as a string. Useful for developers making Wagtail plugins that need to refer to the image model, such as in foreign keys, but the model itself is not required.

업로드 위치 재정의

다음 메서드는 사용자 지정 Image 또는 Rendition 모델에서 재정의하여 원본 및 렌디션 이미지 파일이 저장되는 방식을 사용자 지정할 수 있습니다.

class wagtail.images.models.AbstractImage
get_upload_to(filename)

Generates a file path in the “original_images” folder. Ensuring ASCII characters and limiting length to prevent filesystem issues during uploads.

class wagtail.images.models.AbstractRendition
get_upload_to(filename)

Generates a file path within the “images” folder by combining the folder name and the validated filename.

Django FileField.upload_to 함수를 참조하여 함수가 어떻게 작동하는지 더 자세히 이해하십시오.