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

Issue:
SchemaGenerator add Serializer HiddenFields to parameters
When SchemaGenerator return `.get_schema()` data, HiddenFields included to views parameters:
### Serializer

``` python
class CommonDriverVehiclePOSTSerializer(serializers.ModelSerializer):
    class Meta:
        model = vehicle_mdl.Vehicle
        exclude = ['deleted', ]
        read_only_fields = ['full_name', 'company']

    driver = serializers.HiddenField(default=CurrentDriverProfileDefault())
```
### Generator response

```
post: {
    description: "",
    parameters: [
        {type: "string", name: "driver", required: false, description: "", in: "formData"},
    ],
}
```



Discussion:
Thanks for the report!

Giant thanks for you. DRF is amazing.
Actually, what you think about `channels` project? I try implement it in my last project now. Is it good idea to include support of it to DRF? It may be a first in the world REST framework via Websockets.


Resolving patch:
diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -296,8 +296,9 @@ def get_serializer_fields(self, path, method, callback, view):
 
         fields = []
         for field in serializer.fields.values():
-            if field.read_only:
+            if field.read_only or isinstance(field, serializers.HiddenField):
                 continue
+
             required = field.required and method != 'PATCH'
             description = force_text(field.help_text) if field.help_text else ''
             field = coreapi.Field(


Test patch:
diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -26,6 +26,8 @@ class ExamplePagination(pagination.PageNumberPagination):
 class ExampleSerializer(serializers.Serializer):
     a = serializers.CharField(required=True, help_text='A field description')
     b = serializers.CharField(required=False)
+    read_only = serializers.CharField(read_only=True)
+    hidden = serializers.HiddenField(default='hello')
 
 
 class AnotherSerializer(serializers.Serializer):
Repository: encode/django-rest-framework

Issue:
WIP demonstrating the issue in 4561
## Description

Demonstrates #4561



Discussion:

Resolving patch:
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -507,6 +507,11 @@ def data(self):
     @property
     def errors(self):
         ret = super(Serializer, self).errors
+        if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null':
+            # Edge case. Provide a more descriptive error than
+            # "this field may not be null", when no data is passed.
+            detail = ErrorDetail('No data provided', code='null')
+            ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
         return ReturnDict(ret, serializer=self)
 
 
@@ -700,6 +705,11 @@ def data(self):
     @property
     def errors(self):
         ret = super(ListSerializer, self).errors
+        if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null':
+            # Edge case. Provide a more descriptive error than
+            # "this field may not be null", when no data is passed.
+            detail = ErrorDetail('No data provided', code='null')
+            ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
         if isinstance(ret, dict):
             return ReturnDict(ret, serializer=self)
         return ReturnList(ret, serializer=self)


Test patch:
diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -62,6 +62,12 @@ def create(validated_data):
         with pytest.raises(AssertionError):
             serializer.save()
 
+    def test_validate_none_data(self):
+        data = None
+        serializer = self.Serializer(data=data)
+        assert not serializer.is_valid()
+        assert serializer.errors == {'non_field_errors': ['No data provided']}
+
 
 class TestValidateMethod:
     def test_non_field_error_validate_method(self):
diff --git a/tests/test_serializer_nested.py b/tests/test_serializer_nested.py
--- a/tests/test_serializer_nested.py
+++ b/tests/test_serializer_nested.py
@@ -41,6 +41,12 @@ def test_nested_serialize_empty(self):
         serializer = self.Serializer()
         assert serializer.data == expected_data
 
+    def test_nested_serialize_no_data(self):
+        data = None
+        serializer = self.Serializer(data=data)
+        assert not serializer.is_valid()
+        assert serializer.errors == {'non_field_errors': ['No data provided']}
+
 
 class TestNotRequiredNestedSerializer:
     def setup(self):
Repository: encode/django-rest-framework

Issue:
Invalid prefix in Swagger.
I am using python 2.7 and rest framework 3.5. 
As the title suggests, the prefix is invalid in swagger. It's best shown by this image.
![image](https://cloud.githubusercontent.com/assets/2066100/19593172/f02ac27c-979e-11e6-8582-b1594fc3a0ce.png)
## Expected behavior

The prefixes should have been "api" and "auth" instead of "pi" and "uth".

I suspect that it is due to the behavior of "os.path.commonprefix" in python 2.7



Discussion:
Okay, thanks - can you include a minimal example that demonstrates reproducing the issue?

Confirmed. Register two API views with the URLs given above, and seeing the same issue.

See also http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html


Resolving patch:
diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -1,4 +1,3 @@
-import os
 import re
 from collections import OrderedDict
 from importlib import import_module
@@ -37,6 +36,18 @@
 })
 
 
+def common_path(paths):
+    split_paths = [path.strip('/').split('/') for path in paths]
+    s1 = min(split_paths)
+    s2 = max(split_paths)
+    common = s1
+    for i, c in enumerate(s1):
+        if c != s2[i]:
+            common = s1[:i]
+            break
+    return '/' + '/'.join(common)
+
+
 def get_pk_name(model):
     meta = model._meta.concrete_model._meta
     return _get_pk(meta).name
@@ -292,7 +303,7 @@ def determine_path_prefix(self, paths):
                 # one URL that doesn't have a path prefix.
                 return '/'
             prefixes.append('/' + prefix + '/')
-        return os.path.commonprefix(prefixes)
+        return common_path(prefixes)
 
     def create_view(self, callback, method, request=None):
         """


Test patch:
diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -335,3 +335,14 @@ def test_schema_for_regular_views(self):
             }
         )
         self.assertEqual(schema, expected)
+
+
+@unittest.skipUnless(coreapi, 'coreapi is not installed')
+class Test4605Regression(TestCase):
+    def test_4605_regression(self):
+        generator = SchemaGenerator()
+        prefix = generator.determine_path_prefix([
+            '/api/v1/items/',
+            '/auth/convert-token/'
+        ])
+        assert prefix == '/'
Repository: encode/django-rest-framework

Issue:
BooleanField should also parse 'on'
## 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.)
- [ ] 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.)
## Steps to reproduce

`$(form).serialize()` serialize checkbox with no `value` to "`on`" or "`off`"
## Expected behavior

Add "`on`" to `TRUE_VALUES` and "`off`" to `FALSE_VALUES`
(I don't always have the control over html/js to add `value` to checkboxes).
## Actual behavior

Value is ignored



Discussion:

Resolving patch:
diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -644,8 +644,20 @@ class BooleanField(Field):
     }
     default_empty_html = False
     initial = False
-    TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True}
-    FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False}
+    TRUE_VALUES = {
+        't', 'T',
+        'true', 'True', 'TRUE',
+        'on', 'On', 'ON',
+        '1', 1,
+        True
+    }
+    FALSE_VALUES = {
+        'f', 'F',
+        'false', 'False', 'FALSE',
+        'off', 'Off', 'OFF',
+        '0', 0, 0.0,
+        False
+    }
 
     def __init__(self, **kwargs):
         assert 'allow_null' not in kwargs, '`allow_null` is not a valid option. Use `NullBooleanField` instead.'


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

Issue:
A "pure" HEAD request on a ViewSet does'nt behave like a GET
A HEAD request on a ViewSet let the action attribute empty.
```curl -I http://myhost/api/foo/```

It should fallback to simulate a GET request for everything but the rendering.
Meaning self.action should be either 'list' or 'retrieve'.

Note: ```curl -I -XGET [...]``` behaves as expected.


Discussion:

Resolving patch:
diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py
--- a/rest_framework/viewsets.py
+++ b/rest_framework/viewsets.py
@@ -79,6 +79,9 @@ def view(request, *args, **kwargs):
                 handler = getattr(self, action)
                 setattr(self, method, handler)
 
+            if hasattr(self, 'get') and not hasattr(self, 'head'):
+                self.head = self.get
+
             # And continue as usual
             return self.dispatch(request, *args, **kwargs)
 


Test patch:
diff --git a/tests/test_generics.py b/tests/test_generics.py
--- a/tests/test_generics.py
+++ b/tests/test_generics.py
@@ -101,6 +101,15 @@ def test_get_root_view(self):
         assert response.status_code == status.HTTP_200_OK
         assert response.data == self.data
 
+    def test_head_root_view(self):
+        """
+        HEAD requests to ListCreateAPIView should return 200.
+        """
+        request = factory.head('/')
+        with self.assertNumQueries(1):
+            response = self.view(request).render()
+        assert response.status_code == status.HTTP_200_OK
+
     def test_post_root_view(self):
         """
         POST requests to ListCreateAPIView should create a new object.
diff --git a/tests/test_viewsets.py b/tests/test_viewsets.py
--- a/tests/test_viewsets.py
+++ b/tests/test_viewsets.py
@@ -24,6 +24,15 @@ def test_initialize_view_set_with_actions(self):
         assert response.status_code == status.HTTP_200_OK
         assert response.data == {'ACTION': 'LIST'}
 
+    def testhead_request_against_viewset(self):
+        request = factory.head('/', '', content_type='application/json')
+        my_view = BasicViewSet.as_view(actions={
+            'get': 'list',
+        })
+
+        response = my_view(request)
+        assert response.status_code == status.HTTP_200_OK
+
     def test_initialize_view_set_with_empty_actions(self):
         try:
             BasicViewSet.as_view()
Repository: encode/django-rest-framework

Issue:
#4996 DEFAULT_PAGINATION_CLASS is changed to 'None' in api_settings
because the default value was specified, it did not work properly in API
Document

*Note*: Before submitting this pull request, please review our [contributing guidelines](https://github.com/tomchristie/django-rest-framework/blob/master/CONTRIBUTING.md#pull-requests).

## Description

Please describe your pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue. When linking to an issue, please use `refs #...` in the description of the pull request.



Discussion:

Resolving patch:
diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -600,7 +600,8 @@ def get_pagination_fields(self, path, method, view):
         if not is_list_view(path, method, view):
             return []
 
-        if not getattr(view, 'pagination_class', None):
+        pagination = getattr(view, 'pagination_class', None)
+        if not pagination or not pagination.page_size:
             return []
 
         paginator = view.pagination_class()


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

Issue:
ImproperlyConfigured: Field name `*` is not valid for model `MyModel` with source="*"
https://github.com/encode/django-rest-framework/pull/4688 causes
"ImproperlyConfigured: Field name `*` is not valid for model `MyModel`." when
using `source="*"`.


While DRF 3.6.2 passes `url` to `build_field`, where it gets handled via `build_url_field`, DRF 3.6.3 passes `source` (`*`) there instead.

I will provide a PR with a failing test and a possible fix.



Discussion:

Resolving patch:
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1010,7 +1010,7 @@ def get_fields(self):
                 continue
 
             extra_field_kwargs = extra_kwargs.get(field_name, {})
-            source = extra_field_kwargs.get('source') or field_name
+            source = extra_field_kwargs.get('source', '*') != '*' or field_name
 
             # Determine the serializer field class and keyword arguments.
             field_class, field_kwargs = self.build_field(


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
@@ -524,6 +524,37 @@ class Meta:
         """)
         self.assertEqual(unicode_repr(TestSerializer()), expected)
 
+    def test_nested_hyperlinked_relations_starred_source(self):
+        class TestSerializer(serializers.HyperlinkedModelSerializer):
+            class Meta:
+                model = RelationalModel
+                depth = 1
+                fields = '__all__'
+
+                extra_kwargs = {
+                    'url': {
+                        'source': '*',
+                    }}
+
+        expected = dedent("""
+            TestSerializer():
+                url = HyperlinkedIdentityField(source='*', view_name='relationalmodel-detail')
+                foreign_key = NestedSerializer(read_only=True):
+                    url = HyperlinkedIdentityField(view_name='foreignkeytargetmodel-detail')
+                    name = CharField(max_length=100)
+                one_to_one = NestedSerializer(read_only=True):
+                    url = HyperlinkedIdentityField(view_name='onetoonetargetmodel-detail')
+                    name = CharField(max_length=100)
+                many_to_many = NestedSerializer(many=True, read_only=True):
+                    url = HyperlinkedIdentityField(view_name='manytomanytargetmodel-detail')
+                    name = CharField(max_length=100)
+                through = NestedSerializer(many=True, read_only=True):
+                    url = HyperlinkedIdentityField(view_name='throughtargetmodel-detail')
+                    name = CharField(max_length=100)
+        """)
+        self.maxDiff = None
+        self.assertEqual(unicode_repr(TestSerializer()), expected)
+
     def test_nested_unique_together_relations(self):
         class TestSerializer(serializers.HyperlinkedModelSerializer):
             class Meta:
Repository: encode/django-rest-framework

Issue:
AuthTokenSerializer trims whitespace from passwords
## 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.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)

## Steps to reproduce

1. Create a user with a leading and/or trailing spaces in their password (`User.objects.create(username='foo', password='bar ')`)
1. Attempt to authenticate/validate the user through `AuthTokenSerializer` (`AuthTokenSerializer(data={'username': 'foo', 'password': 'bar '}).is_valid()`)

## Expected behavior

Validation succeeds

## Actual behavior

Validation fails


Discussion:

Resolving patch:
diff --git a/rest_framework/authtoken/serializers.py b/rest_framework/authtoken/serializers.py
--- a/rest_framework/authtoken/serializers.py
+++ b/rest_framework/authtoken/serializers.py
@@ -6,7 +6,11 @@
 
 class AuthTokenSerializer(serializers.Serializer):
     username = serializers.CharField(label=_("Username"))
-    password = serializers.CharField(label=_("Password"), style={'input_type': 'password'})
+    password = serializers.CharField(
+        label=_("Password"),
+        style={'input_type': 'password'},
+        trim_whitespace=False
+    )
 
     def validate(self, attrs):
         username = attrs.get('username')


Test patch:
diff --git a/tests/test_authtoken.py b/tests/test_authtoken.py
--- a/tests/test_authtoken.py
+++ b/tests/test_authtoken.py
@@ -27,3 +27,9 @@ def test_token_string_representation(self):
     def test_validate_raise_error_if_no_credentials_provided(self):
         with pytest.raises(ValidationError):
             AuthTokenSerializer().validate({})
+
+    def test_whitespace_in_password(self):
+        data = {'username': self.user.username, 'password': 'test pass '}
+        self.user.set_password(data['password'])
+        self.user.save()
+        assert AuthTokenSerializer(data=data).is_valid()
Repository: encode/django-rest-framework

Issue:
HiddenField appears in Raw Data form initial content
## 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.
- [x] I have included a ~~failing test~~fix as a pull request. (If you are unable to do so we can still accept the issue.)

## Steps to reproduce

 - create a serializer with a HiddenField
 - create a ModelViewSet referencing that serializer
 - visit the URL corresponding to that ModelViewSet
 - switch to the Raw Data tab and observe that the initial value of the Content textarea is a JSON instance that contains a key for the HiddenField

## Expected behavior

The initial value of the Content textarea is a template JSON instance that contains a key for the HiddenField.

## Actual behavior

The initial value of the Content textarea is a template JSON instance that does not contain a key for the HiddenField.


Discussion:

Resolving patch:
diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -556,7 +556,10 @@ def get_raw_data_form(self, data, view, method, request):
                 accepted = self.accepted_media_type
                 context = self.renderer_context.copy()
                 context['indent'] = 4
-                content = renderer.render(serializer.data, accepted, context)
+                data = {k: v for (k, v) in serializer.data.items()
+                        if not isinstance(serializer.fields[k],
+                                          serializers.HiddenField)}
+                content = renderer.render(data, accepted, context)
             else:
                 content = None
 


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

Issue:
Issue 5220
## Description

The PR includes a testcase for issue #5220  as well as a preliminary fix. What that means is that the fix is working but I believe it could be done in a better way. 






Discussion:

Resolving patch:
diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1137,18 +1137,16 @@ def to_internal_value(self, value):
             if input_format.lower() == ISO_8601:
                 try:
                     parsed = parse_datetime(value)
-                except (ValueError, TypeError):
-                    pass
-                else:
                     if parsed is not None:
                         return self.enforce_timezone(parsed)
+                except (ValueError, TypeError):
+                    pass
             else:
                 try:
                     parsed = self.datetime_parser(value, input_format)
+                    return self.enforce_timezone(parsed)
                 except (ValueError, TypeError):
                     pass
-                else:
-                    return self.enforce_timezone(parsed)
 
         humanized_format = humanize_datetime.datetime_formats(input_formats)
         self.fail('invalid', format=humanized_format)


Test patch:
diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -5,6 +5,7 @@
 import uuid
 from decimal import Decimal
 
+import django
 import pytest
 from django.http import QueryDict
 from django.test import TestCase, override_settings
@@ -1152,6 +1153,7 @@ class TestDateTimeField(FieldValues):
     invalid_inputs = {
         'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
         '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
+        '2018-08-16 22:00-24:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
         datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'],
     }
     outputs = {
@@ -1165,6 +1167,11 @@ class TestDateTimeField(FieldValues):
     field = serializers.DateTimeField(default_timezone=utc)
 
 
+if django.VERSION[:2] <= (1, 8):
+    # Doesn't raise an error on earlier versions of Django
+    TestDateTimeField.invalid_inputs.pop('2018-08-16 22:00-24:00')
+
+
 class TestCustomInputFormatDateTimeField(FieldValues):
     """
     Valid and invalid values for `DateTimeField` with a custom input format.