aboutsummaryrefslogtreecommitdiffstats
path: root/rest_framework/utils/html.py
diff options
context:
space:
mode:
authorXavier Ordoquy2014-11-26 16:36:56 +0100
committerXavier Ordoquy2014-11-26 16:36:56 +0100
commitf5e5ed0077cc477a7b8af98c7b10d8d3701f1a65 (patch)
tree252729a9e61deb0dbc1a098feb1c55eae56ca948 /rest_framework/utils/html.py
parent311d315a739f4d1d02e87a09de0bbf9e7b0cee46 (diff)
parent2647e1aaaadfc2cfd947c633399dca1060c17401 (diff)
downloaddjango-rest-framework-f5e5ed0077cc477a7b8af98c7b10d8d3701f1a65.tar.bz2
Merge remote-tracking branch 'reference/master' into bugfix/1850
Diffstat (limited to 'rest_framework/utils/html.py')
-rw-r--r--rest_framework/utils/html.py88
1 files changed, 88 insertions, 0 deletions
diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py
new file mode 100644
index 00000000..d773952d
--- /dev/null
+++ b/rest_framework/utils/html.py
@@ -0,0 +1,88 @@
+"""
+Helpers for dealing with HTML input.
+"""
+import re
+from django.utils.datastructures import MultiValueDict
+
+
+def is_html_input(dictionary):
+ # MultiDict type datastructures are used to represent HTML form input,
+ # which may have more than one value for each key.
+ return hasattr(dictionary, 'getlist')
+
+
+def parse_html_list(dictionary, prefix=''):
+ """
+ Used to suport list values in HTML forms.
+ Supports lists of primitives and/or dictionaries.
+
+ * List of primitives.
+
+ {
+ '[0]': 'abc',
+ '[1]': 'def',
+ '[2]': 'hij'
+ }
+ -->
+ [
+ 'abc',
+ 'def',
+ 'hij'
+ ]
+
+ * List of dictionaries.
+
+ {
+ '[0]foo': 'abc',
+ '[0]bar': 'def',
+ '[1]foo': 'hij',
+ '[1]bar': 'klm',
+ }
+ -->
+ [
+ {'foo': 'abc', 'bar': 'def'},
+ {'foo': 'hij', 'bar': 'klm'}
+ ]
+ """
+ ret = {}
+ regex = re.compile(r'^%s\[([0-9]+)\](.*)$' % re.escape(prefix))
+ for field, value in dictionary.items():
+ match = regex.match(field)
+ if not match:
+ continue
+ index, key = match.groups()
+ index = int(index)
+ if not key:
+ ret[index] = value
+ elif isinstance(ret.get(index), dict):
+ ret[index][key] = value
+ else:
+ ret[index] = MultiValueDict({key: [value]})
+ return [ret[item] for item in sorted(ret.keys())]
+
+
+def parse_html_dict(dictionary, prefix):
+ """
+ Used to support dictionary values in HTML forms.
+
+ {
+ 'profile.username': 'example',
+ 'profile.email': 'example@example.com',
+ }
+ -->
+ {
+ 'profile': {
+ 'username': 'example',
+ 'email': 'example@example.com'
+ }
+ }
+ """
+ ret = {}
+ regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix))
+ for field, value in dictionary.items():
+ match = regex.match(field)
+ if not match:
+ continue
+ key = match.groups()[0]
+ ret[key] = value
+ return ret