Skip to content

Commit 349218d

Browse files
committed
3.7.8 Add json_for_script function to remove unicode data and escape HTML and XML
-Similar implementation to Django 2.1 function json_script -Fixes the problem where the upload button would not appear if the list had unicode data inside
1 parent ae29a90 commit 349218d

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

filebrowser/templatetags/fb_tags.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from django.utils.safestring import mark_safe
99

1010
from filebrowser.settings import EXTENSIONS, SELECT_FORMATS
11-
11+
from filebrowser.utils import json_for_script
1212

1313
register = template.Library()
1414

@@ -155,7 +155,7 @@ def get_file_extensions(qs):
155155
for item in v:
156156
if item:
157157
extensions.append(item)
158-
return mark_safe(extensions)
158+
return json_for_script(extensions)
159159

160160

161161
# Django 1.9 auto escapes simple_tag unless marked as safe

filebrowser/utils.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,15 @@
44
import os
55
import unicodedata
66
import math
7+
import json
78

9+
from six import iteritems
10+
11+
from django.core.serializers.json import DjangoJSONEncoder
812
from django.utils import six
913
from django.utils.module_loading import import_string
14+
from django.utils.html import format_html
15+
from django.utils.safestring import mark_safe
1016

1117
from filebrowser.settings import STRICT_PIL, NORMALIZE_FILENAME, CONVERT_FILENAME
1218
from filebrowser.settings import VERSION_PROCESSORS
@@ -19,6 +25,32 @@
1925
except ImportError:
2026
import Image
2127

28+
_json_script_escapes = (
29+
('>', '\\u003E'),
30+
('<', '\\u003C'),
31+
('&', '\\u0026'),
32+
)
33+
34+
35+
def json_for_script(value, encoder=DjangoJSONEncoder):
36+
"""
37+
Implementation of json_script from Django 2.1
38+
https://github.com/django/django/commit/8c709d79cbd1a7bb975f58090c17a1178a0efb80
39+
40+
If get_file_extensions is a list of unicode characters, JavaScript is unable to handle it and it will break upload.html
41+
This will convert a list of unicode characters into a regular list, mark it safe, and will escape allthe HTML/XML special
42+
characters with their unicode escapes
43+
"""
44+
json_str = json.dumps(value, cls=encoder)
45+
46+
for bad_char, html_entity in _json_script_escapes:
47+
json_str = json_str.replace(bad_char, html_entity)
48+
49+
return format_html(
50+
'{}',
51+
mark_safe(json_str)
52+
)
53+
2254

2355
def convert_filename(value):
2456
"""

0 commit comments

Comments
 (0)