Allow unsplash images to be used as hero images

This commit is contained in:
Jake Howard 2022-07-12 22:45:50 +01:00
parent a229bb530a
commit b155ec2e9b
Signed by: jake
GPG key ID: 57AFB45680EDD477
5 changed files with 19 additions and 10 deletions

View file

@ -53,6 +53,7 @@ class BlogListPage(BaseContentMixin, BasePage): # type: ignore[misc]
self.get_children()
.live()
.select_related("hero_image")
.select_related("hero_unsplash_photo")
.prefetch_related("tags")
.order_by("-date")
)

View file

@ -1,5 +1,5 @@
import math
from typing import Any
from typing import Any, Optional
from django.db import models
from django.http.request import HttpRequest
@ -7,6 +7,7 @@ from django.utils.functional import cached_property, classproperty
from wagtail.admin.panels import FieldPanel
from wagtail.fields import StreamField
from wagtail.images import get_image_model_string
from wagtail.images.views.serve import generate_image_url
from wagtail.models import Page
from website.common.utils import count_words
@ -19,8 +20,6 @@ from .utils import TocEntry, extract_text, get_table_of_contents, truncate_strin
class BasePage(Page):
show_in_menus_default = True
HERO_IMAGE_SIZE = "width-1200"
class Meta:
abstract = True
@ -86,6 +85,14 @@ class BaseContentMixin(models.Model):
def plain_text(self) -> str:
return extract_text(self.content_html)
@cached_property
def hero_image_url(self) -> Optional[str]:
if self.hero_unsplash_photo_id is not None:
return self.hero_unsplash_photo.get_hero_image_url() # type: ignore
elif self.hero_image_id is not None:
return generate_image_url(self.hero_image, "width-1200")
return None
class ContentPage(BasePage, BaseContentMixin): # type: ignore[misc]
subpage_types: list[Any] = []

View file

@ -1,7 +1,5 @@
{% load wagtailimages_tags %}
{% if page.hero_image %}
<img class="hero" src="{% image_url page.hero_image page.HERO_IMAGE_SIZE %}">
{% if page.hero_image_url %}
<img class="hero" src="{{ page.hero_image_url }}">
{% endif %}
<section class="hero">

View file

@ -1,11 +1,11 @@
{% load wagtailcore_tags wagtailimages_tags %}
{% load wagtailcore_tags %}
<article class="media listing-item">
<div class="columns">
<figure class="media-left column is-3 image-column">
{% if page.hero_image %}
{% if page.hero_image_url %}
<a href="{% pageurl page %}" class="image">
<img src="{% image_url page.hero_image 'width-300' %}">
<img src="{{ page.hero_image_url }}">
</a>
{% endif %}
</figure>

View file

@ -8,5 +8,8 @@ class UnsplashPhoto(models.Model):
def get_description(self) -> str:
return self.data["description"]
def get_hero_image_url(self) -> str:
return self.data["urls"]["regular"]
def get_thumbnail_url(self) -> str:
return self.data["urls"]["thumb"]