Skip to content

Commit 23a2dc3

Browse files
authored
Escape slashes used in placeholer alt text (#39)
* Add test for alt text containing slash character * Encode alt text in placeholder URL Alt texts main contain special chars that are not allowed within URLs. We need to URL escape the alt text when passing it to the placeholder view.
1 parent c216591 commit 23a2dc3

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<picture>{% for type, srcset in sources.items %}
22
<source type="image/{{ type|lower }}"
3-
srcset="{% for width, pic in srcset.items %}{% if use_placeholders %}{% url 'pictures:placeholder' alt ratio width type %}{% else %}{{ pic.url }}{% endif %} {{ width }}w{% if not forloop.last %}, {% endif %}{% endfor %}"
3+
srcset="{% for width, pic in srcset.items %}{% if use_placeholders %}{% url 'pictures:placeholder' alt|urlencode:'' ratio width type %}{% else %}{{ pic.url }}{% endif %} {{ width }}w{% if not forloop.last %}, {% endif %}{% endfor %}"
44
sizes="{{ media }}">{% endfor %}
55
<img src="{{ field_file.url }}" alt="{{ alt }}" width="{{ field_file.width }}" height="{{ field_file.height }}"{% include 'pictures/attrs.html' %}>
66
</picture>

pictures/utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import sys
44
from fractions import Fraction
55
from functools import lru_cache
6+
from urllib.parse import unquote
67

78
from PIL import Image, ImageDraw, ImageFont
89

@@ -81,7 +82,7 @@ def placeholder(width: int, height: int, alt):
8182
elif sys.platform == "darwin":
8283
font_name = "Helvetica"
8384
font = ImageFont.truetype(font_name, fontsize)
84-
text = f"{alt}\n<{width}x{height}>"
85+
text = unquote(f"{alt}\n<{width}x{height}>")
8586
while font.getsize(text)[0] < width / 2:
8687
# iterate until the text size is just larger than the criteria
8788
fontsize += 1

tests/test_templatetags.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@ def test_picture__placeholder(client, image_upload_file, settings):
4040
assert picture_with_placeholders_html in response.content
4141

4242

43+
@pytest.mark.django_db
44+
def test_picture__placeholder_with_alt(client, image_upload_file, settings):
45+
settings.PICTURES["USE_PLACEHOLDERS"] = True
46+
profile = Profile.objects.create(name="Spiderman", picture=image_upload_file)
47+
html = picture(profile.picture, alt="Event 2022/2023", ratio="3/2", loading="lazy")
48+
assert "/_pictures/Event%25202022%252F2023/3x2/800w.WEBP" in html
49+
50+
4351
@pytest.mark.django_db
4452
def test_picture__invalid_ratio(image_upload_file):
4553
profile = Profile.objects.create(name="Spiderman", picture=image_upload_file)

0 commit comments

Comments
 (0)