From 2c52d07b9723296b6c11b4b2c16c26b6263b9928 Mon Sep 17 00:00:00 2001 From: Kalob Taulien Date: Mon, 25 Mar 2019 09:39:48 -0600 Subject: [PATCH] Custom Image Serializer --- blog/models.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/blog/models.py b/blog/models.py index 98504d5..b960c24 100644 --- a/blog/models.py +++ b/blog/models.py @@ -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, @@ -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.""" @@ -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()), ]