Created
August 8, 2019 19:09
-
-
Save bentappin/3bf3c558f8138b852e9fbe8aaf507eab to your computer and use it in GitHub Desktop.
SerpyThumbnailImageField
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import serpy | |
from drf_haystack.serializers import HaystackSerializer | |
from sorl.thumbnail import get_thumbnail | |
class SerpyThumbnailImageField(serpy.StrField): | |
""" | |
A Serpy Field class returning hyperlinked scaled and cached images. | |
Adapted from https://github.com/dessibelle/sorl-thumbnail-serializer-field/ | |
""" | |
def __init__(self, geometry_string, options={}, *args, **kwargs): | |
""" | |
Create an instance of the StrField image serializer. | |
Args: | |
geometry_string (str): The size of your cropped image. | |
options (Optional[dict]): A dict of sorl options. | |
*args: (Optional) Default serializers.ImageField arguments. | |
**kwargs: (Optional) Default serializers.ImageField keyword | |
arguments. | |
For a description of sorl geometry strings and additional sorl options, | |
please see https://sorl-thumbnail.readthedocs.org/en/latest/examples.html?highlight=geometry#low-level-api-examples | |
""" | |
self.geometry_string = geometry_string | |
self.options = options | |
super().__init__(*args, **kwargs) | |
def to_value(self, value): | |
if not value: | |
return None | |
image = get_thumbnail(value, self.geometry_string, **self.options) | |
return image.url |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment