Skip to content

Commit

Permalink
Add placeholders URLs to low level API and contrib DRF
Browse files Browse the repository at this point in the history
  • Loading branch information
codingjoe committed Sep 27, 2022
1 parent a4e6a15 commit 0bcfa38
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
14 changes: 14 additions & 0 deletions pictures/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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
Expand Down
6 changes: 4 additions & 2 deletions tests/contrib/test_rest_framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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)
Expand Down
7 changes: 6 additions & 1 deletion tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 0bcfa38

Please sign in to comment.