Repository: encode/django-rest-framework

Issue:
POST list data breaks all Views / ViewSets
## Checklist

- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)

List data makes any view / viewset crash.

I tested versions from 3.6.3 till 3.7.3 (current pypi) and master.

## Steps to reproduce

Just create simple ApiView / Viewset and serializer (does not matter Serializer or ModelSerializer)

```
from rest_framework import generics, serializers

class TestSerializer(serializers.Serializer):
    value = serializers.IntegerField()

class TestView(generics.CreateAPIView):
    serializer_class = TestSerializer

    def get_queryset(self):
        return TestModel.objects.all()
```

then post JSON data (any array):
`[{}]`

You get stack trace:
```
Internal Server Error: /api/v1/test/
Traceback (most recent call last):
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 217, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 215, in _get_response
    response = response.render()
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/django/template/response.py", line 107, in render
    self.content = self.rendered_content
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/response.py", line 72, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/renderers.py", line 716, in render
    context = self.get_context(data, accepted_media_type, renderer_context)
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/renderers.py", line 689, in get_context
    'post_form': self.get_rendered_html_form(data, view, 'POST', request),
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/renderers.py", line 495, in get_rendered_html_form
    return self.render_form_for_serializer(existing_serializer)
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/renderers.py", line 521, in render_form_for_serializer
    serializer.data,
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/serializers.py", line 533, in data
    ret = super(Serializer, self).data
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/serializers.py", line 266, in data
    self._data = self.get_initial()
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/serializers.py", line 403, in get_initial
    for field_name, field in self.fields.items()
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/serializers.py", line 404, in <listcomp>
    if (field.get_value(self.initial_data) is not empty) and
  File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/fields.py", line 433, in get_value
    return dictionary.get(self.field_name, empty)
```

## Expected behavior

Validation input data type?

## Actual behavior

500


Discussion:
If anyone's looking through the issues and wants to contribute... first thing we need to do here is see if someone else can reproduce and confirm the issue.
@FeroxTL This isn't specific enough to be actionable at the moment. 

* What's the actual exception? You put the traceback by what's the error? 
* `render_form_for_serializer` — So this is for the Browsable API right? What happens for a JSON request? 
* Can you put together a test project that demonstrates this? — It clearly does not apply to just any view or viewset: posting your exact body to [an example endpoint](http://restframework.herokuapp.com/snippets/) give me the expected response: 

```son
{
    "non_field_errors": [
        "Invalid data. Expected a dictionary, but got list."
    ]
}
```

So we need more to be able to reproduce this. (Most likely there's an error elsewhere in your code, but without the exception it's impossible to say...)

I'm going to close this as is. Happy to re-open if we can identify a concrete issue. 

@carltongibson As far as I can see this bug exists in render_form_for_serializer that is used only in Browsable API. So when it gets a list instead of dict is fails.

If Browsable API is turned off (for example
```
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ]
...
```
) this would not be affected. By default it is on.

You need to activate Browsable API (if it is off) and try again. I have created repo with simple test, that shows this bug — https://github.com/FeroxTL/rest_test
Just follow readme.md
Thanks @FeroxTL. I'm reopening this, given the reproduction/test.

Resolving patch:
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -398,6 +398,10 @@ def get_validators(self):
 
     def get_initial(self):
         if hasattr(self, 'initial_data'):
+            # initial_data may not be a valid type
+            if not isinstance(self.initial_data, Mapping):
+                return OrderedDict()
+
             return OrderedDict([
                 (field_name, field.get_value(self.initial_data))
                 for field_name, field in self.fields.items()


Test patch:
diff --git a/tests/browsable_api/test_form_rendering.py b/tests/browsable_api/test_form_rendering.py
--- a/tests/browsable_api/test_form_rendering.py
+++ b/tests/browsable_api/test_form_rendering.py
@@ -14,6 +14,10 @@ class Meta:
         fields = '__all__'
 
 
+class StandardPostView(generics.CreateAPIView):
+    serializer_class = BasicSerializer
+
+
 class ManyPostView(generics.GenericAPIView):
     queryset = BasicModel.objects.all()
     serializer_class = BasicSerializer
@@ -24,6 +28,32 @@ def post(self, request, *args, **kwargs):
         return Response(serializer.data, status.HTTP_200_OK)
 
 
+class TestPostingListData(TestCase):
+    """
+    POSTing a list of data to a regular view should not cause the browsable
+    API to fail during rendering.
+
+    Regression test for https://github.com/encode/django-rest-framework/issues/5637
+    """
+
+    def test_json_response(self):
+        # sanity check for non-browsable API responses
+        view = StandardPostView.as_view()
+        request = factory.post('/', [{}], format='json')
+        response = view(request).render()
+
+        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+        self.assertTrue('non_field_errors' in response.data)
+
+    def test_browsable_api(self):
+        view = StandardPostView.as_view()
+        request = factory.post('/?format=api', [{}], format='json')
+        response = view(request).render()
+
+        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+        self.assertTrue('non_field_errors' in response.data)
+
+
 class TestManyPostView(TestCase):
     def setUp(self):
         """
diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -77,14 +77,23 @@ def test_valid_serializer(self):
         serializer = self.Serializer(data={'char': 'abc', 'integer': 123})
         assert serializer.is_valid()
         assert serializer.validated_data == {'char': 'abc', 'integer': 123}
+        assert serializer.data == {'char': 'abc', 'integer': 123}
         assert serializer.errors == {}
 
     def test_invalid_serializer(self):
         serializer = self.Serializer(data={'char': 'abc'})
         assert not serializer.is_valid()
         assert serializer.validated_data == {}
+        assert serializer.data == {'char': 'abc'}
         assert serializer.errors == {'integer': ['This field is required.']}
 
+    def test_invalid_datatype(self):
+        serializer = self.Serializer(data=[{'char': 'abc'}])
+        assert not serializer.is_valid()
+        assert serializer.validated_data == {}
+        assert serializer.data == {}
+        assert serializer.errors == {'non_field_errors': ['Invalid data. Expected a dictionary, but got list.']}
+
     def test_partial_validation(self):
         serializer = self.Serializer(data={'char': 'abc'}, partial=True)
         assert serializer.is_valid()