django-rest-framework/rest_framework/utils/html.py

96 lines
2.2 KiB
Python
Raw Normal View History

2014-08-29 19:46:26 +04:00
"""
Helpers for dealing with HTML input.
"""
2014-09-02 18:07:56 +04:00
import re
2014-11-06 20:32:33 +03:00
from django.utils.datastructures import MultiValueDict
2014-09-02 18:07:56 +04:00
2014-08-29 19:46:26 +04:00
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='', default=None):
2014-08-29 19:46:26 +04:00
"""
2016-08-08 11:32:22 +03:00
Used to support list values in HTML forms.
2014-08-29 19:46:26 +04:00
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',
2014-11-12 18:38:05 +03:00
'[1]bar': 'klm',
2014-08-29 19:46:26 +04:00
}
-->
[
{'foo': 'abc', 'bar': 'def'},
{'foo': 'hij', 'bar': 'klm'}
]
:returns a list of objects, or the value specified in ``default`` if the list is empty
2014-08-29 19:46:26 +04:00
"""
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:
2014-11-06 20:32:33 +03:00
ret[index] = MultiValueDict({key: [value]})
# return the items of the ``ret`` dict, sorted by key, or ``default`` if the dict is empty
return [ret[item] for item in sorted(ret)] if ret else default
2014-08-29 19:46:26 +04:00
def parse_html_dict(dictionary, prefix=''):
2014-08-29 19:46:26 +04:00
"""
Used to support dictionary values in HTML forms.
{
'profile.username': 'example',
'profile.email': 'example@example.com',
}
-->
{
'profile': {
2014-11-12 18:38:39 +03:00
'username': 'example',
2014-08-29 19:46:26 +04:00
'email': 'example@example.com'
}
}
"""
ret = MultiValueDict()
2014-08-29 19:46:26 +04:00
regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix))
for field in dictionary:
2014-08-29 19:46:26 +04:00
match = regex.match(field)
if not match:
continue
key = match.groups()[0]
value = dictionary.getlist(field)
ret.setlist(key, value)
2014-08-29 19:46:26 +04:00
return ret