Skip to content

Commit 4dffcb5

Browse files
committed
Added humanized field names and types
1 parent 29739f7 commit 4dffcb5

File tree

3 files changed

+148
-2
lines changed

3 files changed

+148
-2
lines changed

rest_framework/fields.py

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,44 @@
2323
from django.utils.datastructures import SortedDict
2424

2525
from rest_framework import ISO_8601
26-
from rest_framework.compat import timezone, parse_date, parse_datetime, parse_time
26+
from rest_framework.compat import (timezone, parse_date, parse_datetime,
27+
parse_time)
2728
from rest_framework.compat import BytesIO
2829
from rest_framework.compat import six
2930
from rest_framework.compat import smart_text
3031
from rest_framework.settings import api_settings
3132

3233

34+
HUMANIZED_FIELD_TYPES = {
35+
'BooleanField': u'Boolean',
36+
'CharField': u'Single Character',
37+
'ChoiceField': u'Single Choice',
38+
'ComboField': u'Single Choice',
39+
'DateField': u'Date',
40+
'DateTimeField': u'Date and Time',
41+
'DecimalField': u'Decimal',
42+
'EmailField': u'Email',
43+
'Field': u'Field',
44+
'FileField': u'File',
45+
'FilePathField': u'File Path',
46+
'FloatField': u'Float',
47+
'GenericIPAddressField': u'Generic IP Address',
48+
'IPAddressField': u'IP Address',
49+
'ImageField': u'Image',
50+
'IntegerField': u'Integer',
51+
'MultiValueField': u'Multiple Value',
52+
'MultipleChoiceField': u'Multiple Choice',
53+
'NullBooleanField': u'Nullable Boolean',
54+
'RegexField': u'Regular Expression',
55+
'SlugField': u'Slug',
56+
'SplitDateTimeField': u'Split Date and Time',
57+
'TimeField': u'Time',
58+
'TypedChoiceField': u'Typed Single Choice',
59+
'TypedMultipleChoiceField': u'Typed Multiple Choice',
60+
'URLField': u'URL',
61+
}
62+
63+
3364
def is_simple_callable(obj):
3465
"""
3566
True if the object is a callable that takes no arguments.
@@ -62,7 +93,8 @@ def get_component(obj, attr_name):
6293

6394

6495
def readable_datetime_formats(formats):
65-
format = ', '.join(formats).replace(ISO_8601, 'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HHMM|-HHMM|Z]')
96+
format = ', '.join(formats).replace(ISO_8601,
97+
'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HHMM|-HHMM|Z]')
6698
return humanize_strptime(format)
6799

68100

@@ -71,6 +103,61 @@ def readable_date_formats(formats):
71103
return humanize_strptime(format)
72104

73105

106+
def humanize_field_type(field_type):
107+
"""Return a human-readable name for a field type.
108+
109+
:param field_type: Either a field type class (for example
110+
django.forms.fields.DateTimeField), or the name of a field type
111+
(for example "DateTimeField").
112+
113+
:return: unicode
114+
115+
"""
116+
if isinstance(field_type, basestring):
117+
field_type_name = field_type
118+
else:
119+
field_type_name = field_type.__name__
120+
try:
121+
return HUMANIZED_FIELD_TYPES[field_type_name]
122+
except KeyError:
123+
humanized = re.sub('([a-z0-9])([A-Z])', r'\1 \2', field_type_name)
124+
return humanized.capitalize()
125+
126+
127+
def humanize_field(field):
128+
"""Return a human-readable description of a field.
129+
130+
:param field: A Django field.
131+
132+
:return: A dictionary of the form {type: type name, required: bool,
133+
label: field label: read_only: bool,
134+
help_text: optional help text}
135+
136+
"""
137+
humanized = {
138+
'type': (field.type_name if field.type_name
139+
else humanize_field_type(field.form_field_class)),
140+
'required': getattr(field, 'required', False),
141+
'label': field.label,
142+
}
143+
optional_attrs = ['read_only', 'help_text']
144+
for attr in optional_attrs:
145+
if hasattr(field, attr):
146+
humanized[attr] = getattr(field, attr)
147+
return humanized
148+
149+
150+
def humanize_form_fields(form):
151+
"""Return a humanized description of all the fields in a form.
152+
153+
:param form: A Django form.
154+
:return: A dictionary of {field_label: humanized description}
155+
156+
"""
157+
fields = SortedDict([(f.name, humanize_field(f)) for f in form.fields])
158+
return fields
159+
160+
74161
def readable_time_formats(formats):
75162
format = ', '.join(formats).replace(ISO_8601, 'hh:mm[:ss[.uuuuuu]]')
76163
return humanize_strptime(format)

rest_framework/tests/fields.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,17 @@
44
from __future__ import unicode_literals
55
from django.utils.datastructures import SortedDict
66
import datetime
7+
from rest_framework.fields import humanize_field, humanize_field_type
8+
from django import forms
79
from decimal import Decimal
810
from django.db import models
911
from django.test import TestCase
1012
from django.core import validators
1113
from rest_framework import serializers
1214
from rest_framework.serializers import Serializer
15+
from rest_framework.fields import Field
16+
from collections import namedtuple
17+
from uuid import uuid4
1318

1419

1520
class TimestampedModel(models.Model):
@@ -685,3 +690,55 @@ def test_choices_not_required(self):
685690
"""
686691
f = serializers.ChoiceField(required=False, choices=self.SAMPLE_CHOICES)
687692
self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + self.SAMPLE_CHOICES)
693+
694+
695+
class HumanizedFieldType(TestCase):
696+
def test_standard_type_classes(self):
697+
for field_type_name in forms.fields.__all__:
698+
field_type = getattr(forms.fields, field_type_name)
699+
humanized = humanize_field_type(field_type)
700+
self.assert_valid_name(humanized)
701+
702+
def test_standard_type_names(self):
703+
for field_type_name in forms.fields.__all__:
704+
humanized = humanize_field_type(field_type_name)
705+
self.assert_valid_name(humanized)
706+
707+
def test_custom_type_name(self):
708+
humanized = humanize_field_type('SomeCustomType')
709+
self.assertEquals(humanized, u'Some custom type')
710+
711+
def test_custom_type(self):
712+
custom_type = namedtuple('SomeCustomType', [])
713+
humanized = humanize_field_type(custom_type)
714+
self.assertEquals(humanized, u'Some custom type')
715+
716+
def assert_valid_name(self, humanized):
717+
"""A humanized field name is valid if it's a non-empty
718+
unicode.
719+
720+
"""
721+
self.assertIsInstance(humanized, unicode)
722+
self.assertTrue(humanized)
723+
724+
725+
class HumanizedField(TestCase):
726+
def setUp(self):
727+
self.required_field = Field()
728+
self.required_field.label = uuid4().hex
729+
self.required_field.required = True
730+
731+
self.optional_field = Field()
732+
self.optional_field.label = uuid4().hex
733+
self.optional_field.required = False
734+
735+
def test_required(self):
736+
self.assertEqual(humanize_field(self.required_field)['required'], True)
737+
738+
def test_optional(self):
739+
self.assertEqual(humanize_field(self.optional_field)['required'],
740+
False)
741+
742+
def test_label(self):
743+
for field in (self.required_field, self.optional_field):
744+
self.assertEqual(humanize_field(field)['label'], field.label)

rest_framework/views.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ def _generate_action_metadata(self, request):
8080
if serializer is not None:
8181
field_name_types = {}
8282
for name, field in serializer.fields.iteritems():
83+
from rest_framework.fields import humanize_field
84+
humanize_field(field)
8385
field_name_types[name] = field.__class__.__name__
8486

8587
actions[method] = field_name_types

0 commit comments

Comments
 (0)