diff --git a/pictures/models.py b/pictures/models.py index 29a8129..5a4c0f1 100644 --- a/pictures/models.py +++ b/pictures/models.py @@ -11,10 +11,12 @@ from django.core.files.storage import Storage from django.db.models import ImageField from django.db.models.fields.files import ImageFieldFile +from django.urls import reverse from PIL import Image, ImageOps __all__ = ["PictureField", "PictureFieldFile"] + from pictures import conf, utils @@ -33,6 +35,18 @@ def __post_init__(self): @property def url(self) -> str: + if conf.get_settings().USE_PLACEHOLDERS: + return reverse( + "pictures:placeholder", + kwargs={ + "alt": Path(self.parent_name).stem, + "width": self.width, + "ratio": f"{self.aspect_ratio.numerator}x{self.aspect_ratio.denominator}" + if self.aspect_ratio + else None, + "file_type": self.file_type, + }, + ) return self.storage.url(self.name) @property diff --git a/tests/contrib/test_rest_framework.py b/tests/contrib/test_rest_framework.py index 9cdc326..aa042c0 100644 --- a/tests/contrib/test_rest_framework.py +++ b/tests/contrib/test_rest_framework.py @@ -18,7 +18,8 @@ class Meta: fields = ["picture"] -def test_default(): +def test_default(settings): + settings.PICTURES["USE_PLACEHOLDERS"] = False assert ( rest_framework.default( obj=SimplePicture( @@ -41,7 +42,8 @@ def test_default__type_error(): class TestPictureField: @pytest.mark.django_db - def test_to_representation(self, image_upload_file): + def test_to_representation(self, image_upload_file, settings): + settings.PICTURES["USE_PLACEHOLDERS"] = False profile = models.Profile.objects.create(picture=image_upload_file) serializer = ProfileSerializer(profile) diff --git a/tests/test_models.py b/tests/test_models.py index 4828af0..4a412b4 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -37,12 +37,17 @@ class TestSimplePicture: width=800, ) - def test_url(self): + def test_url(self, settings): + settings.PICTURES["USE_PLACEHOLDERS"] = False assert ( self.picture_with_ratio.url == "/media/testapp/simplemodel/image/4_3/800w.webp" ) + def test_url__placeholder(self, settings): + settings.PICTURES["USE_PLACEHOLDERS"] = True + assert self.picture_with_ratio.url == "/_pictures/image/4x3/800w.WEBP" + def test_height(self): assert self.picture_with_ratio.height == 600 assert not self.picture_without_ratio.height