Skip to content

Commit

Permalink
feat: add image sizes to news images (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
niccofyren authored Oct 7, 2024
1 parent 67f3d0d commit 4a85a72
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
4 changes: 2 additions & 2 deletions aktuelt/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
from wagtail.admin.panels import FieldPanel, InlinePanel, MultiFieldPanel
from wagtail.api import APIField
from wagtail.fields import RichTextField
from wagtail.images.api.fields import ImageRenditionField
from wagtail.models import Orderable, Page, forms
from wagtail.search import index
from wagtail.snippets.models import register_snippet

from aktuelt.constants import ContributionTypes
from aktuelt.serializers import (
ContributorsSerializer,
NewsImageSerializer,
NewsPageGallerySerializer,
NewsPageTagsSerializer,
)
Expand Down Expand Up @@ -104,7 +104,7 @@ def schedule(self):
APIField("contributors", serializer=ContributorsSerializer(source="news_page_contributors")),
APIField("tags", serializer=NewsPageTagsSerializer()),
APIField("gallery_images", serializer=NewsPageGallerySerializer()),
APIField("main_image", serializer=ImageRenditionField("fill-100x100", source="get_main_image")),
APIField("main_image", serializer=NewsImageSerializer(source="get_main_image")),
]

content_panels = Page.content_panels + [
Expand Down
27 changes: 26 additions & 1 deletion aktuelt/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,31 @@
from wagtail.images.api.fields import ImageRenditionField


class NewsImageSerializer(Field):
def image_size(self, size, value):
image = ImageRenditionField(size).to_representation(value)
return {"url": image["full_url"], "width": image["width"], "height": image["height"]}

def to_representation(self, value):
data = {
"id": value.id,
"title": value.title,
"alt": value.title,
"type": "foto",
"focus": "center",
"author": None,
"sizes": {
"thumbnail": self.image_size("fill-150x150", value),
"small": self.image_size("max-300x300", value),
"medium": self.image_size("max-700x700", value),
"large": self.image_size("max-1600x1600", value),
"extra-large": self.image_size("max-3200x3200", value),
},
}
data["url"] = data["sizes"]["large"]["url"]
return data


class ContributorsSerializer(Field):
def to_representation(self, news_page_contributors):
return [
Expand All @@ -22,7 +47,7 @@ def to_representation(self, value):
return [
# 100% guarantee there are better ways to do this
# TODO: Replace with generic and reusable serializer
ImageRenditionField("fill-100x100").to_representation(gallery_image.image)
NewsImageSerializer().to_representation(gallery_image.image)
for gallery_image in value.all()
]

Expand Down

0 comments on commit 4a85a72

Please sign in to comment.