<a id="custom-image-model"></a>

# 自定义图片模型

`Image` 模型可以自定义，从而为图片添加
额外字段。

为此，你需要在项目中添加两个模型：

- 图片模型本身，继承 `wagtail.images.models.AbstractImage`。你要添加的额外字段就放在这里
- rendition 模型，继承 `wagtail.images.models.AbstractRendition`。它用来存储新模型的 rendition。

下面是一个例子：

```python
# 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` 设置指向它：

```python
WAGTAILIMAGES_IMAGE_MODEL = "images.CustomImage"
```

## 从内置图片模型迁移

把已有站点改为使用自定义图片模型时，不会有任何图片
被自动复制到新模型。把旧图片复制到新
模型需要手动完成，用的是
[数据迁移](https://docs.djangoproject.com/en/stable/topics/migrations/#data-migrations)。

任何引用内置图片模型的模板仍会继续
像以前一样正常工作，但需要更新才能看到新的图片。

<a id="custom-image-model-referring-to-image-model"></a>

## 引用图片模型

### 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.

<a id="custom-image-model-upload-location"></a>

## 覆盖上传位置

你可以在自定义的 `Image` 或 `Rendition` 模型上覆盖以下方法，以自定义原图和 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`](https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.FileField.upload_to) 函数。
