Skip to content

Commit

Permalink
Custom Image Serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
KalobTaulien committed Mar 25, 2019
1 parent 9735b93 commit 2c52d07
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions blog/models.py
Expand Up @@ -7,6 +7,7 @@
from django.shortcuts import render

from modelcluster.fields import ParentalKey, ParentalManyToManyField
from rest_framework.fields import Field
from wagtail.api import APIField
from wagtail.admin.edit_handlers import (
FieldPanel,
Expand All @@ -24,6 +25,19 @@
from streams import blocks


class ImageSerializedField(Field):
"""A custom serializer used in Wagtails v2 API."""

def to_representation(self, value):
"""Return the image URL, title and dimensions."""
return {
"url": value.file.url,
"title": value.title,
"width": value.width,
"height": value.height,
}


class BlogAuthorsOrderable(Orderable):
"""This allows us to select one or more blog authors from Snippets."""

Expand All @@ -45,9 +59,14 @@ def author_name(self):
def author_website(self):
return self.author.website

@property
def author_image(self):
return self.author.image

api_fields = [
APIField("author_name"),
APIField("author_website"),
APIField("author_image", serializer=ImageSerializedField()),
]


Expand Down

1 comment on commit 2c52d07

@KalobTaulien
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.