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

Issue:
Test case for #3598
There is no fix for this test case, just test case which fails.
I don't know how to fix it in a good way.
See more investigation details in issue #3598



Discussion:

Resolving patch:
diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py
--- a/rest_framework/utils/html.py
+++ b/rest_framework/utils/html.py
@@ -80,10 +80,12 @@ def parse_html_dict(dictionary, prefix=''):
     """
     ret = MultiValueDict()
     regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix))
-    for field, value in dictionary.items():
+    for field in dictionary:
         match = regex.match(field)
         if not match:
             continue
         key = match.groups()[0]
-        ret[key] = value
+        value = dictionary.getlist(field)
+        ret.setlist(key, value)
+
     return ret


Test patch:
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
@@ -167,3 +167,32 @@ def test_empty_not_allowed_if_allow_empty_is_set_to_false(self):
 
         expected_errors = {'not_allow_empty': {'non_field_errors': [serializers.ListSerializer.default_error_messages['empty']]}}
         assert serializer.errors == expected_errors
+
+
+class TestNestedSerializerWithList:
+    def setup(self):
+        class NestedSerializer(serializers.Serializer):
+            example = serializers.MultipleChoiceField(choices=[1, 2, 3])
+
+        class TestSerializer(serializers.Serializer):
+            nested = NestedSerializer()
+
+        self.Serializer = TestSerializer
+
+    def test_nested_serializer_with_list_json(self):
+        input_data = {
+            'nested': {
+                'example': [1, 2],
+            }
+        }
+        serializer = self.Serializer(data=input_data)
+
+        assert serializer.is_valid()
+        assert serializer.validated_data['nested']['example'] == set([1, 2])
+
+    def test_nested_serializer_with_list_multipart(self):
+        input_data = QueryDict('nested.example=1&nested.example=2')
+        serializer = self.Serializer(data=input_data)
+
+        assert serializer.is_valid()
+        assert serializer.validated_data['nested']['example'] == set([1, 2])
Repository: encode/django-rest-framework

Issue:
Re-add conditional abstract setting to Token model
When attempting to use [a custom model](https://github.com/incuna/django-user-management/blob/master/user_management/api/models.py#L42) instead of DRF's built-in `Token`, Django tries very hard to include the `Token` model even if `rest_framework.authtoken` isn't in `INSTALLED_APPS`.  Attempting to run migrations on a fresh database will explode with a missing user model error, and an already-set-up database will have a `Token` table added to it (which also means the user model gets an unwanted `auth_token` `OneToOne` field on it).

I believe a simple fix for this behaviour is to reinstate [the `Meta` `abstract` setting](https://github.com/tomchristie/django-rest-framework/blob/af0ea8ef5136da30cb058b10a493d36619d24add/rest_framework/authtoken/models.py#L24-L30) in the `Token` model.  I spent a day or so digging for other ways to avoid using `Token` in the project I was working on and couldn't find anything, but there may also be other fixes.



Discussion:
Should be fixed by #3785

Unfortunately, that's the exact commit that introduces the breakage.  The delayed import doesn't seem to help.  I haven't been able to figure out why.

When I was experimenting and trying to figure out how to work around this, I even deleted the entire `TokenAuthentication` class, and the problem persisted.  I think the `Token` model is being picked up through other means.

(We're on Django 1.8.)

Do you have some sample project to reproduce the issue ?

Not at the moment (it's a private project).  I'll try to get some time to make one.  I imagine it would involve:
- `rest_framework` in `INSTALLED_APPS` (but not `rest_framework.authtoken`)
- A `User` model exists and `AUTH_USER_MODEL` is set
- A test calls `_meta.get_all_field_names()` on that user model

I don't know if the migration ordering issue will occur for the test project - it depends on whether `Token` is migrated before `User`.  If it does, trying to run the tests will blow up with the SQL error about a missing relation.  If that error doesn't appear, the test should show that `auth_token` is a field on the `User` model.

Now that I read this again, I think I get the issue and indeed the Token should be left abstract if the app isn't in the INSTALLED_APPS.

:+1: Thanks :)


Resolving patch:
diff --git a/rest_framework/authtoken/models.py b/rest_framework/authtoken/models.py
--- a/rest_framework/authtoken/models.py
+++ b/rest_framework/authtoken/models.py
@@ -22,6 +22,14 @@ class Token(models.Model):
                                 on_delete=models.CASCADE)
     created = models.DateTimeField(auto_now_add=True)
 
+    class Meta:
+        # Work around for a bug in Django:
+        # https://code.djangoproject.com/ticket/19422
+        #
+        # Also see corresponding ticket:
+        # https://github.com/tomchristie/django-rest-framework/issues/705
+        abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS
+
     def save(self, *args, **kwargs):
         if not self.key:
             self.key = self.generate_key()


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

Issue:
Use Pandoc to publish RestructuredText to PyPI
A little call out to Pandoc during the `publish` setup.py command would mean this:

![screen shot 2016-01-08 at 6 49 35 pm](https://cloud.githubusercontent.com/assets/62857/12213963/abb63344-b638-11e5-9882-11d13fe809af.png)

would look more like: 

![screen shot 2016-01-08 at 6 50 59 pm](https://cloud.githubusercontent.com/assets/62857/12213970/cdad432a-b638-11e5-95a8-36323af1d04a.png)

If this is something wanted, I'm more than happy to make the pull request.



Discussion:
I'd be ok if we just had moved our `README.md` to reStructuredText instead. That file only changes when a new version is released.

@pydanny sounds good. I'd probably rather see/review that first, before considering using .rst for the README


Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -7,6 +7,17 @@
 
 from setuptools import setup
 
+try:
+    from pypandoc import convert
+
+    def read_md(f):
+        return convert(f, 'rst')
+except ImportError:
+    print("warning: pypandoc module not found, could not convert Markdown to RST")
+
+    def read_md(f):
+        return open(f, 'r').read()
+
 
 def get_version(package):
     """
@@ -45,6 +56,10 @@ def get_package_data(package):
 
 
 if sys.argv[-1] == 'publish':
+    try:
+        import pypandoc
+    except ImportError:
+        print("pypandoc not installed.\nUse `pip install pypandoc`.\nExiting.")
     if os.system("pip freeze | grep wheel"):
         print("wheel not installed.\nUse `pip install wheel`.\nExiting.")
         sys.exit()
@@ -68,6 +83,7 @@ def get_package_data(package):
     url='http://www.django-rest-framework.org',
     license='BSD',
     description='Web APIs for Django, made easy.',
+    long_description=read_md('README.md'),
     author='Tom Christie',
     author_email='tom@tomchristie.com',  # SEE NOTE BELOW (*)
     packages=get_packages('rest_framework'),


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

Issue:
Field.initial does not accept callables
While trying to use the `Field.initial` property just like I'm used to do that with regular Django fields, in DRF this property does not accept a callable. When rendering serializer fields in HTML the `initial` becomes something like `<function func_name_here0x0000000>`

Example:

```
def some_callable():
    return uuid4().hex

class FooSerializer(serializers.Serializer):
    test_field = serializers.CharField(initial=some_callable)
```

The expected behaviour (in a default Django field) would be a input with a `uuid` as it's initial value, but DRF tries to render the function object.



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
@@ -370,6 +370,8 @@ def get_initial(self):
         Return a value to use when the field is being returned as a primitive
         value, without any object instance.
         """
+        if callable(self.initial):
+            return self.initial()
         return self.initial
 
     def get_value(self, dictionary):


Test patch:
diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -191,6 +191,24 @@ def test_initial(self):
         }
 
 
+class TestInitialWithCallable:
+    def setup(self):
+        def initial_value():
+            return 123
+
+        class TestSerializer(serializers.Serializer):
+            initial_field = serializers.IntegerField(initial=initial_value)
+        self.serializer = TestSerializer()
+
+    def test_initial_should_accept_callable(self):
+        """
+        Follows the default ``Field.initial`` behaviour where they accept a
+        callable to produce the initial value"""
+        assert self.serializer.data == {
+            'initial_field': 123,
+        }
+
+
 class TestLabel:
     def setup(self):
         class TestSerializer(serializers.Serializer):
Repository: encode/django-rest-framework

Issue:
Support customized CSRF token cookie name
## 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.)
## Steps to reproduce
1. Activate `SessionAuthentication` for all views, or a single view.
2. Set [`CSRF_COOKIE_NAME`](https://docs.djangoproject.com/en/1.8/ref/settings/#csrf-cookie-name) to a non-default value.
3. Login.
4. Navigate to a view secured by `SessionAuthentication` via the Browseable API.
5. Attempt to a PATCH/POST/PUT operation.
## Expected behavior

The action should be completed successfully.
## Actual behavior

The action fails with HTTP status 403, and the message `CSRF Failed: CSRF token missing or incorrect.`.

csrf.js has the cookie name hardcoded: https://github.com/tomchristie/django-rest-framework/blob/bb56ca46ed6c07db0146dbdc61c672ff25f127de/rest_framework/static/rest_framework/js/csrf.js#L36. It should instead get the cookie name from settings.



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
@@ -12,6 +12,7 @@
 from collections import OrderedDict
 
 from django import forms
+from django.conf import settings
 from django.core.exceptions import ImproperlyConfigured
 from django.core.paginator import Page
 from django.http.multipartparser import parse_header
@@ -657,7 +658,8 @@ def get_context(self, data, accepted_media_type, renderer_context):
 
             'display_edit_forms': bool(response.status_code != 403),
 
-            'api_settings': api_settings
+            'api_settings': api_settings,
+            'csrf_cookie_name': settings.CSRF_COOKIE_NAME,
         }
         return context
 


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

Issue:
TimeField render returns None instead of 00:00:00
## 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.)
## Steps to reproduce
1. Create a model A with a TimeField B in it.
2. Create an instance C of the model A in which the TimeField B has a "00:00:00" value (midnight).
3. Create a default DRF serializer D for the model A.
4. Render the object C through serializer D
## Expected behavior

It should render the TimeField B as "00:00:00".
## Actual behavior

It actually gets rendered as None.



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
@@ -1191,7 +1191,7 @@ def to_internal_value(self, value):
         self.fail('invalid', format=humanized_format)
 
     def to_representation(self, value):
-        if not value:
+        if value in (None, ''):
             return None
 
         output_format = getattr(self, 'format', api_settings.TIME_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
@@ -1063,7 +1063,8 @@ class TestTimeField(FieldValues):
         '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]].'],
     }
     outputs = {
-        datetime.time(13, 00): '13:00:00',
+        datetime.time(13, 0): '13:00:00',
+        datetime.time(0, 0): '00:00:00',
         '00:00:00': '00:00:00',
         None: None,
         '': None,
Repository: encode/django-rest-framework

Issue:
Serializers with many=True should return empty list rather than empty dict
Follow up proposal fix for #3434 and #3437



Discussion:
@tomchristie this is ready for a review

I think I need to dig a bit why we get a dictionary in the first place. Feels like the root cause isn't fixed with this PR.


Resolving patch:
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -667,6 +667,28 @@ def save(self, **kwargs):
 
         return self.instance
 
+    def is_valid(self, raise_exception=False):
+        # This implementation is the same as the default,
+        # except that we use lists, rather than dicts, as the empty case.
+        assert hasattr(self, 'initial_data'), (
+            'Cannot call `.is_valid()` as no `data=` keyword argument was '
+            'passed when instantiating the serializer instance.'
+        )
+
+        if not hasattr(self, '_validated_data'):
+            try:
+                self._validated_data = self.run_validation(self.initial_data)
+            except ValidationError as exc:
+                self._validated_data = []
+                self._errors = exc.detail
+            else:
+                self._errors = []
+
+        if self._errors and raise_exception:
+            raise ValidationError(self.errors)
+
+        return not bool(self._errors)
+
     def __repr__(self):
         return unicode_to_repr(representation.list_repr(self, indent=1))
 


Test patch:
diff --git a/tests/test_serializer_bulk_update.py b/tests/test_serializer_bulk_update.py
--- a/tests/test_serializer_bulk_update.py
+++ b/tests/test_serializer_bulk_update.py
@@ -46,6 +46,7 @@ def test_bulk_create_success(self):
         serializer = self.BookSerializer(data=data, many=True)
         self.assertEqual(serializer.is_valid(), True)
         self.assertEqual(serializer.validated_data, data)
+        self.assertEqual(serializer.errors, [])
 
     def test_bulk_create_errors(self):
         """
@@ -76,6 +77,7 @@ def test_bulk_create_errors(self):
         serializer = self.BookSerializer(data=data, many=True)
         self.assertEqual(serializer.is_valid(), False)
         self.assertEqual(serializer.errors, expected_errors)
+        self.assertEqual(serializer.validated_data, [])
 
     def test_invalid_list_datatype(self):
         """
Repository: encode/django-rest-framework

Issue:
DateTimeField to_representation can handle strings. Fixes #4013.
Fixes issue with DateTimeField described in #4013.



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
@@ -1073,7 +1073,7 @@ def to_representation(self, value):
 
         output_format = getattr(self, 'format', api_settings.DATETIME_FORMAT)
 
-        if output_format is None:
+        if output_format is None or isinstance(value, six.string_types):
             return value
 
         if output_format.lower() == ISO_8601:
@@ -1133,7 +1133,7 @@ def to_representation(self, value):
 
         output_format = getattr(self, 'format', api_settings.DATE_FORMAT)
 
-        if output_format is None:
+        if output_format is None or isinstance(value, six.string_types):
             return value
 
         # Applying a `DateField` to a datetime value is almost always
@@ -1146,8 +1146,6 @@ def to_representation(self, value):
         )
 
         if output_format.lower() == ISO_8601:
-            if isinstance(value, six.string_types):
-                value = datetime.datetime.strptime(value, '%Y-%m-%d').date()
             return value.isoformat()
 
         return value.strftime(output_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
@@ -993,6 +993,8 @@ class TestDateTimeField(FieldValues):
     outputs = {
         datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00',
         datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): '2001-01-01T13:00:00Z',
+        '2001-01-01T00:00:00': '2001-01-01T00:00:00',
+        six.text_type('2016-01-10T00:00:00'): '2016-01-10T00:00:00',
         None: None,
         '': None,
     }
Repository: encode/django-rest-framework

Issue:
Two slightly different iso 8601 datetime serialization
## 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.)
## Steps to reproduce

The implementation of datetime serialization in ISO-8601 format is not consistent in the codebase.
In https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py#L1094 microseconds are included in the serialized value
In https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/encoders.py#L30 only milliseconds are
## Expected behavior

I would expect a consistent implementation.
## Actual behavior

N/A



Discussion:

Resolving patch:
diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py
--- a/rest_framework/utils/encoders.py
+++ b/rest_framework/utils/encoders.py
@@ -28,8 +28,6 @@ def default(self, obj):
             return force_text(obj)
         elif isinstance(obj, datetime.datetime):
             representation = obj.isoformat()
-            if obj.microsecond:
-                representation = representation[:23] + representation[26:]
             if representation.endswith('+00:00'):
                 representation = representation[:-6] + 'Z'
             return representation


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

Issue:
Serializing "complex" field returns None instead of the value since 3.4
(Not a great title — I hope the description will clarify.)
## Steps to reproduce

First: `pip install django-phonenumber-field`

With the following model and serializer:

``` python
from django.db.models import Model
from phonenumber_field.modelfields import PhoneNumberField
from rest_framework.serializers import ModelSerializer

class PhoneModel(Model):
    number = PhoneNumberField()

class PhoneSerializer(ModelSerializer):
    class Meta:
        model = PhoneModel
        fields = ['number']
```
## Expected behavior

This test used to pass (until version 3.3.3):

``` python
def test_phone_serializer():
    phone = models.PhoneModel(number='+33610293847')
    data = models.PhoneSerializer(phone).data
    assert data['number'] == '+33610293847'
```
## Actual behavior

The test fails (since version 3.4) with:

```
    def test_phone_serializer():
        phone = models.PhoneModel(number='+33610293847')
        data = models.PhoneSerializer(phone).data
>       assert data['number'] == '+33610293847'
E       assert None == '+33610293847'
```
## Analysis

I bisected this regression to 9c996d7d2aa4137c8ba29afa2253efec8d6db74f.

As far as I can tell, DRF used to get the string representation of the field and no longer does.

```
(Pdb) phone.number
PhoneNumber(country_code=33, national_number=610293847, extension=None, italian_leading_zero=None, number_of_leading_zeros=None, country_code_source=1, preferred_domestic_carrier_code='')
(Pdb) str(phone.number)
'+33610293847'
```



Discussion:
Actually you seem to be missing a `return` here: https://github.com/tomchristie/django-rest-framework/commit/9c996d7d2aa4137c8ba29afa2253efec8d6db74f#diff-ce493f71b3679e91b72126c168670399R128


Resolving patch:
diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -125,7 +125,7 @@ def get_related_model(field):
 def value_from_object(field, obj):
     if django.VERSION < (1, 9):
         return field._get_val_from_obj(obj)
-    field.value_from_object(obj)
+    return field.value_from_object(obj)
 
 
 # contrib.postgres only supported from 1.8 onwards.


Test patch: