Skip to content

Commit 0bcfa38

Browse files
committed
Add placeholders URLs to low level API and contrib DRF
1 parent a4e6a15 commit 0bcfa38

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

pictures/models.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@
1111
from django.core.files.storage import Storage
1212
from django.db.models import ImageField
1313
from django.db.models.fields.files import ImageFieldFile
14+
from django.urls import reverse
1415
from PIL import Image, ImageOps
1516

1617
__all__ = ["PictureField", "PictureFieldFile"]
1718

19+
1820
from pictures import conf, utils
1921

2022

@@ -33,6 +35,18 @@ def __post_init__(self):
3335

3436
@property
3537
def url(self) -> str:
38+
if conf.get_settings().USE_PLACEHOLDERS:
39+
return reverse(
40+
"pictures:placeholder",
41+
kwargs={
42+
"alt": Path(self.parent_name).stem,
43+
"width": self.width,
44+
"ratio": f"{self.aspect_ratio.numerator}x{self.aspect_ratio.denominator}"
45+
if self.aspect_ratio
46+
else None,
47+
"file_type": self.file_type,
48+
},
49+
)
3650
return self.storage.url(self.name)
3751

3852
@property

tests/contrib/test_rest_framework.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ class Meta:
1818
fields = ["picture"]
1919

2020

21-
def test_default():
21+
def test_default(settings):
22+
settings.PICTURES["USE_PLACEHOLDERS"] = False
2223
assert (
2324
rest_framework.default(
2425
obj=SimplePicture(
@@ -41,7 +42,8 @@ def test_default__type_error():
4142

4243
class TestPictureField:
4344
@pytest.mark.django_db
44-
def test_to_representation(self, image_upload_file):
45+
def test_to_representation(self, image_upload_file, settings):
46+
settings.PICTURES["USE_PLACEHOLDERS"] = False
4547

4648
profile = models.Profile.objects.create(picture=image_upload_file)
4749
serializer = ProfileSerializer(profile)

tests/test_models.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,17 @@ class TestSimplePicture:
3737
width=800,
3838
)
3939

40-
def test_url(self):
40+
def test_url(self, settings):
41+
settings.PICTURES["USE_PLACEHOLDERS"] = False
4142
assert (
4243
self.picture_with_ratio.url
4344
== "/media/testapp/simplemodel/image/4_3/800w.webp"
4445
)
4546

47+
def test_url__placeholder(self, settings):
48+
settings.PICTURES["USE_PLACEHOLDERS"] = True
49+
assert self.picture_with_ratio.url == "/_pictures/image/4x3/800w.WEBP"
50+
4651
def test_height(self):
4752
assert self.picture_with_ratio.height == 600
4853
assert not self.picture_without_ratio.height

0 commit comments

Comments
 (0)