diff --git a/rest_framework_docs/api_endpoint.py b/rest_framework_docs/api_endpoint.py index 953f9a0..fab7947 100644 --- a/rest_framework_docs/api_endpoint.py +++ b/rest_framework_docs/api_endpoint.py @@ -6,6 +6,7 @@ from rest_framework.viewsets import ModelViewSet from rest_framework.serializers import BaseSerializer +from rest_framework.serializers import PrimaryKeyRelatedField VIEWSET_METHODS = { 'List': ['get', 'post'], @@ -122,13 +123,33 @@ def __get_serializer_fields__(self, serializer): "type": str(field.__class__.__name__), "sub_fields": sub_fields, "required": field.required, - "to_many_relation": to_many_relation + "to_many_relation": to_many_relation, + "choices": self.__get_field_choices(field), }) # FIXME: # Show more attibutes of `field`? return fields + def __get_field_choices(self, field): + """If it's a related field returns an one element list with the + related model. If the field has choices returns the + choices. Else returns `None` + + """ + if isinstance(field, PrimaryKeyRelatedField): + return ['Related field ' + str(field.queryset.model)] + + if hasattr(field, 'choices'): + # Force choice keys to be a string or `json.dumps` fails + # This happens when using django-timezone-field where + # choices are a object. + if isinstance(field.choices, dict): + if not all(map(lambda x: isinstance(x, str), field.choices.keys())): + choices = dict([(str(key), field.choices[key]) for key in field.choices.keys()]) + return choices + return field.choices + def __get_serializer_fields_json__(self): # FIXME: # Return JSON or not? diff --git a/rest_framework_docs/templates/rest_framework_docs/components/fields_list.html b/rest_framework_docs/templates/rest_framework_docs/components/fields_list.html index a351946..f0b6f04 100644 --- a/rest_framework_docs/templates/rest_framework_docs/components/fields_list.html +++ b/rest_framework_docs/templates/rest_framework_docs/components/fields_list.html @@ -10,6 +10,16 @@ Array of objects {% endif %} + {% if field.choices %} +

Choices +

+

+ {% endif %} + {% if field.sub_fields %} {%include "rest_framework_docs/components/fields_list.html" with fields=field.sub_fields %} {% endif %}