Skip to content

Commit

Permalink
Fix ValueError for DRF fields if field value is blank
Browse files Browse the repository at this point in the history
  • Loading branch information
codingjoe committed Jun 8, 2023
1 parent 9f0c956 commit 98d3934
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 1 deletion.
2 changes: 2 additions & 0 deletions pictures/contrib/rest_framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class PictureField(serializers.ReadOnlyField):
"""Read-only field for all aspect ratios and sizes of the image."""

def to_representation(self, obj: PictureFieldFile):
if not obj:
return None
payload = {
"url": obj.url,
"width": obj.width,
Expand Down
14 changes: 14 additions & 0 deletions tests/contrib/test_rest_framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,20 @@ def test_to_representation__raise_value_error(

assert str(e.value) == "Invalid ratio: 21/11. Choices are: 1/1, 3/2, 16/9"

@pytest.mark.django_db
def test_to_representation__blank(self, rf, image_upload_file, settings):
settings.PICTURES["USE_PLACEHOLDERS"] = False

profile = models.Profile.objects.create()
request = rf.get("/")
request.GET._mutable = True
request.GET["picture_ratio"] = "21/11"
request.GET["picture_l"] = "3"
request.GET["picture_m"] = "4"
serializer = ProfileSerializer(profile, context={"request": request})

assert serializer.data["picture"] is None

@pytest.mark.django_db
def test_to_representation__with_container(self, rf, image_upload_file, settings):
settings.PICTURES["USE_PLACEHOLDERS"] = False
Expand Down
27 changes: 27 additions & 0 deletions tests/testapp/migrations/0005_alter_profile_picture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Generated by Django 3.2.19 on 2023-06-07 18:06

from django.db import migrations
import pictures.models


class Migration(migrations.Migration):
dependencies = [
("testapp", "0004_jpegmodel"),
]

operations = [
migrations.AlterField(
model_name="profile",
name="picture",
field=pictures.models.PictureField(
aspect_ratios=[None, "1/1", "3/2", "16/9"],
blank=True,
breakpoints={"l": 1200, "m": 992, "s": 768, "xl": 1400, "xs": 576},
container_width=1200,
file_types=["WEBP"],
grid_columns=12,
pixel_densities=[1, 2],
upload_to="testapp/profile/",
),
),
]
4 changes: 3 additions & 1 deletion tests/testapp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ class JPEGModel(models.Model):
class Profile(models.Model):
name = models.CharField(max_length=100)
picture = PictureField(
upload_to="testapp/profile/", aspect_ratios=[None, "1/1", "3/2", "16/9"]
upload_to="testapp/profile/",
aspect_ratios=[None, "1/1", "3/2", "16/9"],
blank=True,
)

def get_absolute_url(self):
Expand Down

0 comments on commit 98d3934

Please sign in to comment.