internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: encode/django-rest-framework

Issue:
ListField seems to miss single values
The [get_value](https://github.com/tomchristie/django-rest-framework/blob/37b4d4248895e1583861af863a3906f582e4cd0c/rest_framework/fields.py#L1382) method of `ListField` seems to use `if len(val) > 1:` where I believe it ought to be `if len(val) >= 1:` or `if len(val) > 0:`

In a Django `QueryDict`, for example, `getlist` will yield a list of 1 item even if there is _only_ one item. This seems to miss all the paths currently defined.

By way of example, here's a quick sketch of what I believe is demonstrable of the issue I think we're having:

```
>>> from rest_framework.fields import ListField
>>> from django.http import QueryDict
>>> qs = QueryDict('foo=1')
[u'1']
>>> qs2 = QueryDict('foo=1&foo=2')
[u'1', u'2']
>>> field = ListField()
>>> field.field_name = 'foo'  # for the purposes of getting the prefix right
>>> field.get_value(qs2)
[u'1', u'2']
>>> field.get_value(qs)
[]
```

I'd expect the last, empty list `[]` to be `[u'1']`
This is against drf `3.2.0` and Django `1.8.x`



Discussion:
What's the behavior against 3.1.3?
Would you be able to create a failing test case pull request for this?

with `pip install djangorestframework==3.1.3` and the same code, both querydicts (`qs`, `qs2`) yield `[]` when thrown through `get_value`, so the new one is _better_, but not quite what I'd hope for.

I ought to be able to produce a PR for it, if testing at this level, rather than a instrumenting from a higher level, is acceptable.


Resolving patch:
diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1384,7 +1384,7 @@ def get_value(self, dictionary):
         # lists in HTML forms.
         if html.is_html_input(dictionary):
             val = dictionary.getlist(self.field_name, [])
-            if len(val) > 1:
+            if len(val) > 0:
                 # Support QueryDict lists in HTML input.
                 return val
             return html.parse_html_list(dictionary, prefix=self.field_name)


Test patch:
diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -317,6 +317,14 @@ class TestSerializer(serializers.Serializer):
         assert serializer.is_valid()
         assert serializer.validated_data == {'scores': [1, 3]}
 
+    def test_querydict_list_input_only_one_input(self):
+        class TestSerializer(serializers.Serializer):
+            scores = serializers.ListField(child=serializers.IntegerField())
+
+        serializer = TestSerializer(data=QueryDict('scores=1&'))
+        assert serializer.is_valid()
+        assert serializer.validated_data == {'scores': [1]}
+
 
 class TestCreateOnlyDefault:
     def setup(self):
Repository: encode/django-rest-framework

Issue:
Response should raise an error if passed a serializer instance
We should guard against accidental `Response(serializer)`, with an error stating "You probably meant serializer.data or serializer.errors".



Discussion:

Resolving patch:
diff --git a/rest_framework/response.py b/rest_framework/response.py
--- a/rest_framework/response.py
+++ b/rest_framework/response.py
@@ -10,6 +10,8 @@
 from django.utils import six
 from django.utils.six.moves.http_client import responses
 
+from rest_framework.serializers import Serializer
+
 
 class Response(SimpleTemplateResponse):
     """
@@ -28,6 +30,15 @@ def __init__(self, data=None, status=None,
         For example being set automatically by the `APIView`.
         """
         super(Response, self).__init__(None, status=status)
+
+        if isinstance(data, Serializer):
+            msg = (
+                'You passed a Serializer instance as data, but '
+                'probably meant to pass serialized `.data` or '
+                '`.error`. representation.'
+            )
+            raise AssertionError(msg)
+
         self.data = data
         self.template_name = template_name
         self.exception = exception


Test patch:
Repository: encode/django-rest-framework

Issue:
TypeError when search_fields is omitted
Contrary to documentation, if SearchFilter is added but search_fields accidentally (or on purpose) omitted, DRF Release 3.2.3 presents a TypeError when listing a ViewSet. This behavior was not present in Release 3.2.2.

TypeError when search_fields is omitted
Contrary to documentation, if SearchFilter is added but search_fields accidentally (or on purpose) omitted, DRF Release 3.2.3 presents a TypeError when listing a ViewSet. This behavior was not present in Release 3.2.2.



Discussion:

Resolving patch:
diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -102,15 +102,16 @@ def construct_search(self, field_name):
     def filter_queryset(self, request, queryset, view):
         search_fields = getattr(view, 'search_fields', None)
 
-        orm_lookups = [
-            self.construct_search(six.text_type(search_field))
-            for search_field in search_fields
-        ]
         search_terms = self.get_search_terms(request)
 
         if not search_fields or not search_terms:
             return queryset
 
+        orm_lookups = [
+            self.construct_search(six.text_type(search_field))
+            for search_field in search_fields
+        ]
+
         base = queryset
         for search_term in search_terms:
             queries = [


Test patch:
Repository: encode/django-rest-framework

Issue:
Keep max_length when converting TextField to CharField in ModelSerializer
When Django makes a ModelForm out of a Model it validates the max_length of any TextFields (if specified) even though it is not enforced on a database level. I realize this did not use to be the case and that may be why DRF does not currently do the same with ModelSerializers. I see no downside to having them do the same. Currently `TextField(max_length=1000)` becomes `CharField(style={'base_template': 'textarea.html'})`.



Discussion:
Seems valid.

Working on this.


Resolving patch:
diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py
--- a/rest_framework/utils/field_mapping.py
+++ b/rest_framework/utils/field_mapping.py
@@ -123,7 +123,8 @@ def get_field_kwargs(field_name, model_field):
     # Ensure that max_length is passed explicitly as a keyword arg,
     # rather than as a validator.
     max_length = getattr(model_field, 'max_length', None)
-    if max_length is not None and isinstance(model_field, models.CharField):
+    if max_length is not None and (isinstance(model_field, models.CharField) or
+                                   isinstance(model_field, models.TextField)):
         kwargs['max_length'] = max_length
         validator_kwarg = [
             validator for validator in validator_kwarg


Test patch:
diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py
--- a/tests/test_model_serializer.py
+++ b/tests/test_model_serializer.py
@@ -63,7 +63,7 @@ class RegularFieldsModel(models.Model):
     positive_small_integer_field = models.PositiveSmallIntegerField()
     slug_field = models.SlugField(max_length=100)
     small_integer_field = models.SmallIntegerField()
-    text_field = models.TextField()
+    text_field = models.TextField(max_length=100)
     time_field = models.TimeField()
     url_field = models.URLField(max_length=100)
     custom_field = CustomField()
@@ -161,11 +161,12 @@ class Meta:
                 positive_small_integer_field = IntegerField()
                 slug_field = SlugField(max_length=100)
                 small_integer_field = IntegerField()
-                text_field = CharField(style={'base_template': 'textarea.html'})
+                text_field = CharField(max_length=100, style={'base_template': 'textarea.html'})
                 time_field = TimeField()
                 url_field = URLField(max_length=100)
                 custom_field = ModelField(model_field=<tests.test_model_serializer.CustomField: custom_field>)
         """)
+
         self.assertEqual(unicode_repr(TestSerializer()), expected)
 
     def test_field_options(self):
Repository: encode/django-rest-framework

Issue:
Django 1.9 raw HTML in header
I just upgraded to 3.2.4 and this is what I see:

<img width="1002" alt="screen shot 2015-10-25 at 8 35 12 pm" src="https://cloud.githubusercontent.com/assets/54896/10714927/f175ae3a-7b57-11e5-94ab-bb253219113f.png">



Discussion:
Notes on how to replicate would be great, as we've not had this raised elsewhere. Does it replicate on a clean install, and what exact steps are required?

Oh yea, I just replicated this.

```
$ git clone https://github.com/tomchristie/rest-framework-tutorial.git
$ pip install -r requirements.txt
$ pip install --upgrade --pre django
$ pip install --upgrade djangorestframework
$ ./manage.py runserver
```

Might be because of this [change on simple_tag on Django 1.9](https://docs.djangoproject.com/en/1.9/releases/1.9/#simple-tag-now-wraps-tag-output-in-conditional-escape). Checking it out.


Resolving patch:
diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py
--- a/rest_framework/templatetags/rest_framework.py
+++ b/rest_framework/templatetags/rest_framework.py
@@ -7,7 +7,7 @@
 from django.template import Context, loader
 from django.utils import six
 from django.utils.encoding import force_text, iri_to_uri
-from django.utils.html import escape, smart_urlquote
+from django.utils.html import escape, format_html, smart_urlquote
 from django.utils.safestring import SafeData, mark_safe
 
 from rest_framework.renderers import HTMLFormRenderer
@@ -48,7 +48,8 @@ def optional_login(request):
         return ''
 
     snippet = "<li><a href='{href}?next={next}'>Log in</a></li>"
-    snippet = snippet.format(href=login_url, next=escape(request.path))
+    snippet = format_html(snippet, href=login_url, next=escape(request.path))
+
     return mark_safe(snippet)
 
 
@@ -71,7 +72,8 @@ def optional_logout(request, user):
             <li><a href='{href}?next={next}'>Log out</a></li>
         </ul>
     </li>"""
-    snippet = snippet.format(user=escape(user), href=logout_url, next=escape(request.path))
+    snippet = format_html(snippet, user=escape(user), href=logout_url, next=escape(request.path))
+
     return mark_safe(snippet)
 
 


Test patch:
Repository: encode/django-rest-framework

Issue:
Viewsets without a filter_class break Browser Viewer
The `to_html` function doesn't check if the `cls` exists in this line:

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L121

It should have logic checking for a `None`, similar to the above bit:

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L112-L114

Causes this error when viewing those pages: `'NoneType' object is not callable`

Viewsets without a filter_class break Browser Viewer
The `to_html` function doesn't check if the `cls` exists in this line:

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L121

It should have logic checking for a `None`, similar to the above bit:

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L112-L114

Causes this error when viewing those pages: `'NoneType' object is not callable`



Discussion:

Resolving patch:
diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -117,8 +117,11 @@ def filter_queryset(self, request, queryset, view):
         return queryset
 
     def to_html(self, request, queryset, view):
-        cls = self.get_filter_class(view, queryset)
-        filter_instance = cls(request.query_params, queryset=queryset)
+        filter_class = self.get_filter_class(view, queryset)
+        if filter_class:
+            filter_instance = filter_class(request.query_params, queryset=queryset)
+        else:
+            filter_instance = None
         context = Context({
             'filter': filter_instance
         })


Test patch:
Repository: encode/django-rest-framework

Issue:
HTML form in generics.listCreateAPI is not taking values
When we try to submit json through the HTML form where the view is created with ListCreateAPI, it is not saving the values. If we save it using the application/json, it saves the values.
This was working fine in version 3.2.5 but it is not working in version 3.3.0



Discussion:

Resolving patch:
diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py
--- a/rest_framework/__init__.py
+++ b/rest_framework/__init__.py
@@ -8,7 +8,7 @@
 """
 
 __title__ = 'Django REST framework'
-__version__ = '3.2.4'
+__version__ = '3.3.0'
 __author__ = 'Tom Christie'
 __license__ = 'BSD 2-Clause'
 __copyright__ = 'Copyright 2011-2015 Tom Christie'
diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py
--- a/rest_framework/authentication.py
+++ b/rest_framework/authentication.py
@@ -117,9 +117,8 @@ def authenticate(self, request):
         Otherwise returns `None`.
         """
 
-        # Get the underlying HttpRequest object
-        request = request._request
-        user = getattr(request, 'user', None)
+        # Get the session-based user from the underlying HttpRequest object
+        user = getattr(request._request, 'user', None)
 
         # Unauthenticated, CSRF validation not required
         if not user or not user.is_active:
diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -365,6 +365,15 @@ def DATA(self):
             'since version 3.0, and has been fully removed as of version 3.2.'
         )
 
+    @property
+    def POST(self):
+        # Ensure that request.POST uses our request parsing.
+        if not _hasattr(self, '_data'):
+            self._load_data_and_files()
+        if is_form_media_type(self.content_type):
+            return self.data
+        return QueryDict('', encoding=self._request._encoding)
+
     @property
     def FILES(self):
         # Leave this one alone for backwards compat with Django's request.FILES


Test patch:
Repository: encode/django-rest-framework

Issue:
Assumes primary key called `id`, breaks HyperlinkedModelSerializer
Does [this line](https://github.com/tomchristie/django-rest-framework/blob/3.3.0/rest_framework/serializers.py#L1134) assume now that the primary key of a model is called `id`?

In the past the `ModelSerializer` generated (In this case the primary key on the `Order` model is `order_id`):

```
order = PrimaryKeyRelatedField(read_only=True)
```

Now I get:

```
order = SlugRelatedField(read_only=True, slug_field='order_id')
```

The issue comes up in that if instead I use a `HyperlinkedModelSerializer`, I no longer get a hyperlink for that field.



Discussion:
@cancan101 it indeed looks like it assumes the PK to be "id" which doesn't look right.

Looks like this was relatively recent PR: https://github.com/tomchristie/django-rest-framework/pull/3526.


Resolving patch:
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1131,7 +1131,7 @@ def build_relational_field(self, field_name, relation_info):
         field_kwargs = get_relation_kwargs(field_name, relation_info)
 
         to_field = field_kwargs.pop('to_field', None)
-        if to_field and to_field != 'id':
+        if to_field and not relation_info.related_model._meta.get_field(to_field).primary_key:
             field_kwargs['slug_field'] = to_field
             field_class = self.serializer_related_to_field
 


Test patch:
Repository: encode/django-rest-framework

Issue:
Hyperlink Class Cannot Be Pickled
Related to #3350, the `rest_framework.relations.Hyperlink` instances cannot be pickled as demonstrated with this sample:

```
>>> import pickle
>>> from rest_framework.relations import Hyperlink
>>> link = Hyperlink('http://example.com', 'test')
>>> pickle.loads(pickle.dumps(link))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: __new__() missing 1 required positional argument: 'name'
```

For serializers which use the hyperlink relations, this breaks the caching of the response objects since most of the cache backends rely on pickle by default.

Hyperlink Class Cannot Be Pickled
Related to #3350, the `rest_framework.relations.Hyperlink` instances cannot be pickled as demonstrated with this sample:

```
>>> import pickle
>>> from rest_framework.relations import Hyperlink
>>> link = Hyperlink('http://example.com', 'test')
>>> pickle.loads(pickle.dumps(link))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: __new__() missing 1 required positional argument: 'name'
```

For serializers which use the hyperlink relations, this breaks the caching of the response objects since most of the cache backends rely on pickle by default.



Discussion:
Thanks a lot @mlavin. I think this can be linked to another issue where cache was failing with a similar message though we were not able to identify where it did come from.

Thanks a lot @mlavin. I think this can be linked to another issue where cache was failing with a similar message though we were not able to identify where it did come from.


Resolving patch:
diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -32,6 +32,9 @@ def __new__(self, url, name):
         ret.name = name
         return ret
 
+    def __getnewargs__(self):
+        return(str(self), self.name,)
+
     is_hyperlink = True
 
 


Test patch:
diff --git a/tests/test_relations.py b/tests/test_relations.py
--- a/tests/test_relations.py
+++ b/tests/test_relations.py
@@ -206,3 +206,14 @@ def test_get_value_multi_dictionary_partial(self):
 
         mvd = MultiValueDict({'baz': ['bar1', 'bar2']})
         assert empty == self.field.get_value(mvd)
+
+
+class TestHyperlink:
+    def setup(self):
+        self.default_hyperlink = serializers.Hyperlink('http://example.com', 'test')
+
+    def test_can_be_pickled(self):
+        import pickle
+        upkled = pickle.loads(pickle.dumps(self.default_hyperlink))
+        assert upkled == self.default_hyperlink
+        assert upkled.name == self.default_hyperlink.name
Repository: encode/django-rest-framework

Issue:
URLPathVersioning should maybe remove the version_param kwarg from subsequent view dispatch?
I've been playing around with getting `URLPathVersioning` working properly, and have discovered what might be a bug, or maybe just undocumented (or obvious and expected) behaviour.

urlconf contains:

```
from rest_framework.authtoken.views import obtain_auth_token
# ...

api_patterns = [
    url(r'^', include(router.urls), name='api-root'),
    url(r'^auth-token/', obtain_auth_token, name='api-auth-token'),
]
urlpatterns = [
    url(r'^api/(?P<version>v\d{1,})/', include(api_patterns)),
    # ...
]
```

When testing, with something like:

```
url = reverse('api-auth-token', kwargs=dict(version='v1'))
self.client.post(url, data, format='json')
```

I get an exception that ultimately ends in:

```
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 463, in dispatch
    response = handler(request, *args, **kwargs)
TypeError: post() got an unexpected keyword argument 'version'
```

Investigation shows that the `ObtainAuthToken.post()` method doesn't accept any kwargs, so it's clearly failing because it's getting version passed in by default from the rest of the versionating mechanism.

Simplest fix would be to just fix the definition of `ObtainAuthToken.post(self, request, **kwargs)`, 
but it made me wonder if it'll be an issue for other views that are receiving a somewhat unexpected kwarg, and which is by intent already available to them in `request.version`.

If there's no good reason to keep it around after extracting it, would it make sense to clean it from the
view args in `views.APIView` somewhere in the initial pre-dispatch phases, maybe as simple as a
`kwargs.pop(request.versioning_scheme.version_param, None)` (with some checks around it) in the appropriate place?

I'm currently subclassing `authtoken.ObtainAuthToken` to do exactly this in `post()`, but I figured it might make sense to raise a a more general issue.



Discussion:
I'd rather fix the AuthToken to accept the extra kwarg.

Thanks for reporting.

> I'd rather fix the AuthToken to accept the extra kwarg.

Seems reasonable.


Resolving patch:
diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py
--- a/rest_framework/authtoken/views.py
+++ b/rest_framework/authtoken/views.py
@@ -12,7 +12,7 @@ class ObtainAuthToken(APIView):
     renderer_classes = (renderers.JSONRenderer,)
     serializer_class = AuthTokenSerializer
 
-    def post(self, request):
+    def post(self, request, *args, **kwargs):
         serializer = self.serializer_class(data=request.data)
         serializer.is_valid(raise_exception=True)
         user = serializer.validated_data['user']


Test patch:
Repository: encode/django-rest-framework

Issue:
Rest Framework Settings file Performs an O(n) operation on settings access that could be O(1)
Calling .keys() on a dictionary returns an iterable, so doing a membership test against that iterable is an O(n) operation. By not including a call to .keys(), the same effect will be attained in O(1) time.

https://github.com/tomchristie/django-rest-framework/blob/af0ea8ef5136da30cb058b10a493d36619d24add/rest_framework/settings.py#L199



Discussion:
@CuriousG102 mind submitting a PR to discuss further?

Sounds like a smal improvement since values are cached after that but still possible

Ah. I didn't notice the caching going on on line 214. That does indeed make this a small improvement. Otherwise it might have been a bit bigger depending on how often settings are accessed. In any case I'll make a PR after New Years celebrations.

Thanks and enjoy the celebrations !


Resolving patch:
diff --git a/rest_framework/settings.py b/rest_framework/settings.py
--- a/rest_framework/settings.py
+++ b/rest_framework/settings.py
@@ -196,7 +196,7 @@ def user_settings(self):
         return self._user_settings
 
     def __getattr__(self, attr):
-        if attr not in self.defaults.keys():
+        if attr not in self.defaults:
             raise AttributeError("Invalid API setting: '%s'" % attr)
 
         try:


Test patch: