Skip to content

Commit 98d3934

Browse files
committed
Fix ValueError for DRF fields if field value is blank
1 parent 9f0c956 commit 98d3934

File tree

4 files changed

+46
-1
lines changed

4 files changed

+46
-1
lines changed

pictures/contrib/rest_framework.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ class PictureField(serializers.ReadOnlyField):
2020
"""Read-only field for all aspect ratios and sizes of the image."""
2121

2222
def to_representation(self, obj: PictureFieldFile):
23+
if not obj:
24+
return None
2325
payload = {
2426
"url": obj.url,
2527
"width": obj.width,

tests/contrib/test_rest_framework.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,20 @@ def test_to_representation__raise_value_error(
168168

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

171+
@pytest.mark.django_db
172+
def test_to_representation__blank(self, rf, image_upload_file, settings):
173+
settings.PICTURES["USE_PLACEHOLDERS"] = False
174+
175+
profile = models.Profile.objects.create()
176+
request = rf.get("/")
177+
request.GET._mutable = True
178+
request.GET["picture_ratio"] = "21/11"
179+
request.GET["picture_l"] = "3"
180+
request.GET["picture_m"] = "4"
181+
serializer = ProfileSerializer(profile, context={"request": request})
182+
183+
assert serializer.data["picture"] is None
184+
171185
@pytest.mark.django_db
172186
def test_to_representation__with_container(self, rf, image_upload_file, settings):
173187
settings.PICTURES["USE_PLACEHOLDERS"] = False
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Generated by Django 3.2.19 on 2023-06-07 18:06
2+
3+
from django.db import migrations
4+
import pictures.models
5+
6+
7+
class Migration(migrations.Migration):
8+
dependencies = [
9+
("testapp", "0004_jpegmodel"),
10+
]
11+
12+
operations = [
13+
migrations.AlterField(
14+
model_name="profile",
15+
name="picture",
16+
field=pictures.models.PictureField(
17+
aspect_ratios=[None, "1/1", "3/2", "16/9"],
18+
blank=True,
19+
breakpoints={"l": 1200, "m": 992, "s": 768, "xl": 1400, "xs": 576},
20+
container_width=1200,
21+
file_types=["WEBP"],
22+
grid_columns=12,
23+
pixel_densities=[1, 2],
24+
upload_to="testapp/profile/",
25+
),
26+
),
27+
]

tests/testapp/models.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@ class JPEGModel(models.Model):
3535
class Profile(models.Model):
3636
name = models.CharField(max_length=100)
3737
picture = PictureField(
38-
upload_to="testapp/profile/", aspect_ratios=[None, "1/1", "3/2", "16/9"]
38+
upload_to="testapp/profile/",
39+
aspect_ratios=[None, "1/1", "3/2", "16/9"],
40+
blank=True,
3941
)
4042

4143
def get_absolute_url(self):

0 commit comments

Comments
 (0)