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

Issue:
3.6.4 Release
Checklist:

- [x] Create pull request for [release notes](https://github.com/tomchristie/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [3.6.4 milestone](https://github.com/tomchristie/django-rest-framework/milestones/***). PR: #5344
- [x] Bump remaining unclosed issues. 
- [x] Update the translations from [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).
- [x] Ensure the pull request increments the version to `3.6.4` in [`restframework/__init__.py`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/__init__.py).
- [x] Confirm with @tomchristie that release is finalized and ready to go.
- [x] Ensure that release date is included in pull request.
- [x] Merge the release pull request.
- [x] Push the package to PyPI with `./setup.py publish`.
- [x] Tag the release, with `git tag -a 3.6.4 -m 'version 3.6.4'; git push --tags`.
- [x] Deploy the documentation with `mkdocs gh-deploy`.
- [x] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).
- [x] Make a release announcement on twitter.
- [x] Close the milestone on GitHub.



Discussion:
Target for this is over-the-weekend, possibly into Monday.

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.6.3'
+__version__ = '3.6.4'
 __author__ = 'Tom Christie'
 __license__ = 'BSD 2-Clause'
 __copyright__ = 'Copyright 2011-2017 Tom Christie'


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

Issue:
SchemaGenerator:get_description break markdown syntax
This shema using for django-rest-swagger

[This](https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas.py#L479) code delete start/end spaces in descriptions. 
```
 lines = [line.strip() for line in description.splitlines()]
```

But spaces is a part markdown syntax!

Where is it important:

- list
    - sublist
```
- list
    - sublist
```

    code

```
    code
```


Discussion:
Yep. This seems valid. 

[`get_view_description` already handles `dedent`-ing](https://github.com/encode/django-rest-framework/blob/master/rest_framework/views.py#L51), so is this doing anything here? 

@aklim007: a failing test case with your example would be a good start to a PR here. ;-)

Resolving patch:
diff --git a/rest_framework/schemas/inspectors.py b/rest_framework/schemas/inspectors.py
--- a/rest_framework/schemas/inspectors.py
+++ b/rest_framework/schemas/inspectors.py
@@ -207,7 +207,7 @@ def get_description(self, path, method):
             return formatting.dedent(smart_text(method_docstring))
 
         description = view.get_view_description()
-        lines = [line.strip() for line in description.splitlines()]
+        lines = [line for line in description.splitlines()]
         current_section = ''
         sections = {'': ''}
 


Test patch:
diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -15,6 +15,7 @@
     AutoSchema, ManualSchema, SchemaGenerator, get_schema_view
 )
 from rest_framework.test import APIClient, APIRequestFactory
+from rest_framework.utils import formatting
 from rest_framework.views import APIView
 from rest_framework.viewsets import ModelViewSet
 
@@ -577,3 +578,38 @@ class CustomView(APIView):
         view = CustomView()
         link = view.schema.get_link(path, method, base_url)
         assert link == expected
+
+
+def test_docstring_is_not_stripped_by_get_description():
+    class ExampleDocstringAPIView(APIView):
+        """
+        === title
+
+         * item a
+           * item a-a
+           * item a-b
+         * item b
+
+         - item 1
+         - item 2
+
+            code block begin
+            code
+            code
+            code
+            code block end
+
+        the end
+        """
+
+        def get(self, *args, **kwargs):
+            pass
+
+        def post(self, request, *args, **kwargs):
+            pass
+
+    view = ExampleDocstringAPIView()
+    schema = view.schema
+    descr = schema.get_description('example', 'get')
+    # the first and last character are '\n' correctly removed by get_description
+    assert descr == formatting.dedent(ExampleDocstringAPIView.__doc__[1:][:-1])
Repository: encode/django-rest-framework

Issue:
Inconsistent time 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 time 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#L1284 microseconds are included in the serialized value
In https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/encoders.py#L41 only milliseconds are

This is basically the same issue as #4255 except for time instead of datetime.

## Expected behavior
I would expect a consistent implementation between the different serialization of time _and_ datetime, i.e. all of them should include microseconds.

## Actual behavior
See "Steps to reproduce"


Discussion:
Yup seems clear. Milestoning for 3.7 so we can make to make the change against a major version (given that it'll change the API output)

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
@@ -37,8 +37,6 @@ def default(self, obj):
             if timezone and timezone.is_aware(obj):
                 raise ValueError("JSON can't represent timezone-aware times.")
             representation = obj.isoformat()
-            if obj.microsecond:
-                representation = representation[:12]
             return representation
         elif isinstance(obj, datetime.timedelta):
             return six.text_type(total_seconds(obj))


Test patch:
diff --git a/tests/test_encoders.py b/tests/test_encoders.py
--- a/tests/test_encoders.py
+++ b/tests/test_encoders.py
@@ -44,7 +44,7 @@ def test_encode_time(self):
         Tests encoding a timezone
         """
         current_time = datetime.now().time()
-        assert self.encoder.default(current_time) == current_time.isoformat()[:12]
+        assert self.encoder.default(current_time) == current_time.isoformat()
 
     def test_encode_time_tz(self):
         """
Repository: encode/django-rest-framework

Issue:
Update checks.py
refs: #5170 
## Description
If statement caused the error in normal cases without the solution before.
so I changed if statement to check only in user-settings and give solution and hint to handle that error


Discussion:

Resolving patch:
diff --git a/rest_framework/checks.py b/rest_framework/checks.py
--- a/rest_framework/checks.py
+++ b/rest_framework/checks.py
@@ -12,7 +12,10 @@ def pagination_system_check(app_configs, **kwargs):
                 "You have specified a default PAGE_SIZE pagination rest_framework setting,"
                 "without specifying also a DEFAULT_PAGINATION_CLASS.",
                 hint="The default for DEFAULT_PAGINATION_CLASS is None. "
-                     "In previous versions this was PageNumberPagination",
+                     "In previous versions this was PageNumberPagination. "
+                     "If you wish to define PAGE_SIZE globally whilst defining "
+                     "pagination_class on a per-view basis you may silence this check.",
+                id="rest_framework.W001"
             )
         )
     return errors


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

Issue:
Unhanded exception is wsgiref (py3) caused from CreateModelMixin
## 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

## Steps to reproduce
- python3.x (reporduceable on 3.4 - 3.6)
- Install django 2.0beta & latest DRF
- Create simple model
- Create simple HyperlinkedModelSerializer that uses 'url' field instead of 'id'
- Create simple viewset
- run standard django runserver (wsgiref)
- POST new model

## Expected behavior

- model gets created without any issues

## Actual behavior

- models is created but:
- Exception is raised by wsgiref from here https://github.com/python/cpython/blob/3.6/Lib/wsgiref/headers.py#L43

The issue is that header is of type `Hyperlink`, and wsgiref explicitly checks for `str` only
It's caused here: https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py#L30
The data is not a `str`



Discussion:
@canni Thanks for the report. Any chance you could post a minimal test project so we can quickly reproduce this? 

Can you also post the full traceback so we can see that? `get_success_headers` is meant to return a `dict` so the problem isn't there exactly. 

Our test suite is [passing against Django `master`](https://travis-ci.org/encode/django-rest-framework/jobs/294611809) — so we must be missing a test somewhere.

The reproduce steps seem simple enough. This must be new: what changed and where? (Is this even our bug...?)
> so we must be missing a test somewhere

The wsgiref tests are just more particular about WSGI conformance.
Unlikely that this is actually causing any issues with server implementations, since we've not had it raised in any other context, but we could wrap that expression with `str(...)` for completeness.

Resolving patch:
diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py
--- a/rest_framework/mixins.py
+++ b/rest_framework/mixins.py
@@ -27,7 +27,7 @@ def perform_create(self, serializer):
 
     def get_success_headers(self, data):
         try:
-            return {'Location': data[api_settings.URL_FIELD_NAME]}
+            return {'Location': str(data[api_settings.URL_FIELD_NAME])}
         except (TypeError, KeyError):
             return {}
 


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

Issue:
Wheels include .DS_Store files.
## Steps to reproduce

* Download latest wheel from PyPI (currently https://pypi.python.org/pypi/djangorestframework/3.7.3, https://pypi.python.org/packages/f5/2c/3c3c81b8ecd60952c20ccd5fc1d19c0b22731c80c75649dd2e3fef361aaf/djangorestframework-3.7.3-py2.py3-none-any.whl#md5=ee78a9aaddc972e9bf75ebaa4c0d6ff5)
* List the files in the wheel
* Search for DS_Store in the results

## Expected behavior

No hits.

## Actual behavior

```
unzip -l djangorestframework-3.7.3-py2.py3-none-any.whl | grep DS
     6148  07-01-2014 01:42   rest_framework/templates/.DS_Store
     6148  09-28-2017 10:00   rest_framework/templates/rest_framework/.DS_Store
```


Discussion:
I think the issue here is the use of `package_data`. Since we provide a `MANIFEST.in`, we should be able to just use `include_package_data=True`. 
Incoming `Fix MANIFEST.in` commit... 😀 

Thanks for the report @sjoerdjob. We'll sort it for the next release. 

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -6,7 +6,7 @@
 import sys
 from io import open
 
-from setuptools import setup
+from setuptools import setup, find_packages
 
 try:
     from pypandoc import convert
@@ -28,31 +28,6 @@ def get_version(package):
     return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
 
 
-def get_packages(package):
-    """
-    Return root package and all sub-packages.
-    """
-    return [dirpath
-            for dirpath, dirnames, filenames in os.walk(package)
-            if os.path.exists(os.path.join(dirpath, '__init__.py'))]
-
-
-def get_package_data(package):
-    """
-    Return all files under the root package, that are not in a
-    package themselves.
-    """
-    walk = [(dirpath.replace(package + os.sep, '', 1), filenames)
-            for dirpath, dirnames, filenames in os.walk(package)
-            if not os.path.exists(os.path.join(dirpath, '__init__.py'))]
-
-    filepaths = []
-    for base, filenames in walk:
-        filepaths.extend([os.path.join(base, filename)
-                          for filename in filenames])
-    return {package: filepaths}
-
-
 version = get_version('rest_framework')
 
 
@@ -84,8 +59,8 @@ def get_package_data(package):
     long_description=read_md('README.md'),
     author='Tom Christie',
     author_email='tom@tomchristie.com',  # SEE NOTE BELOW (*)
-    packages=get_packages('rest_framework'),
-    package_data=get_package_data('rest_framework'),
+    packages=find_packages(exclude=['tests*']),
+    include_package_data=True,
     install_requires=[],
     zip_safe=False,
     classifiers=[


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

As reported in #4012, the pandoc reST output is not rendering properly on PyPI. PyPI doesn't really report these errors easily so here is some output that can hopefully help resolve the problem. On other projects, when I've resolved any errors from rst2html, the page starts to render properly on PyPI.

``` bash
python setup.py --long-description | rst2html.py > /dev/null
<stdin>:110: (WARNING/2) Cannot analyze code. Pygments package not found.
<stdin>:145: (WARNING/2) Cannot analyze code. Pygments package not found.
```

Installing Pygments made the errors go away.

@mblayman We already have a fix for that, see the related issues list.

I ran the above command from the stable branch that includes the merged PR referenced in the issues list. I did some triage and thought this might be new information.

My apologies if you were already aware of this.


Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -9,10 +9,10 @@
 from setuptools import setup
 
 try:
-    from pypandoc import convert
+    from pypandoc import convert_file
 
     def read_md(f):
-        return convert(f, 'rst')
+        return convert_file(f, 'rst')
 except ImportError:
     print("warning: pypandoc module not found, could not convert Markdown to RST")
 


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

Issue:
Add failing test for to_representation with explicit default timezone
See discussion here:
    https://github.com/encode/django-rest-framework/pull/5435#issuecomment-364054509

*Note*: Before submitting this pull request, please review our [contributing guidelines](https://github.com/encode/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/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1212,8 +1212,9 @@ def to_representation(self, value):
         if output_format is None or isinstance(value, six.string_types):
             return value
 
+        value = self.enforce_timezone(value)
+
         if output_format.lower() == ISO_8601:
-            value = self.enforce_timezone(value)
             value = value.isoformat()
             if value.endswith('+00:00'):
                 value = value[:-6] + 'Z'


Test patch:
diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -9,7 +9,7 @@
 from django.http import QueryDict
 from django.test import TestCase, override_settings
 from django.utils import six
-from django.utils.timezone import activate, deactivate, utc
+from django.utils.timezone import activate, deactivate, override, utc
 
 import rest_framework
 from rest_framework import compat, serializers
@@ -1296,6 +1296,27 @@ def test_current_timezone(self):
         assert self.field.default_timezone() == utc
 
 
+@pytest.mark.skipif(pytz is None, reason='pytz not installed')
+@override_settings(TIME_ZONE='UTC', USE_TZ=True)
+class TestCustomTimezoneForDateTimeField(TestCase):
+
+    @classmethod
+    def setup_class(cls):
+        cls.kolkata = pytz.timezone('Asia/Kolkata')
+        cls.date_format = '%d/%m/%Y %H:%M'
+
+    def test_should_render_date_time_in_default_timezone(self):
+        field = serializers.DateTimeField(default_timezone=self.kolkata, format=self.date_format)
+        dt = datetime.datetime(2018, 2, 8, 14, 15, 16, tzinfo=pytz.utc)
+
+        with override(self.kolkata):
+            rendered_date = field.to_representation(dt)
+
+        rendered_date_in_timezone = dt.astimezone(self.kolkata).strftime(self.date_format)
+
+        assert rendered_date == rendered_date_in_timezone
+
+
 class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
     """
     Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST.
Repository: encode/django-rest-framework

Issue:
RelatedField (and their subclasses) do not support traversing relationships that can be null
This was introduced by #5518, and while the solutions there work on normal fields, RelatedField behaves differently:

https://github.com/encode/django-rest-framework/blob/da535d31dd93dbb1d650e2e92bd0910ca8eb4ea4/rest_framework/fields.py#L440-L442

vs

https://github.com/encode/django-rest-framework/blob/da535d31dd93dbb1d650e2e92bd0910ca8eb4ea4/rest_framework/relations.py#L177

An example of the problem can be reproduced with https://gist.github.com/gcbirzan/a968facbaf0969f4a9616942de7022dc

A `Model1` instance with `None` for `model2` will produce an exception.

I believe that the correct behaviour is for `RelatedField.get_attribute` to call super. 

As a side note, this is very hacky to work around, you'll need to copy paste the code from `RelatedField.get_attribute` in your class, then call the `Field.get_attribute`, since obviously super won't work.

If there's some agreement that this is the solution, I can fix it, but I'm not 100% sure (given the reaction on the original ticket) if this is considered a bug.


Discussion:

Resolving patch:
diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -174,7 +174,7 @@ def get_attribute(self, instance):
                 pass
 
         # Standard case, return the object instance.
-        return get_attribute(instance, self.source_attrs)
+        return super(RelatedField, self).get_attribute(instance)
 
     def get_choices(self, cutoff=None):
         queryset = self.get_queryset()


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
@@ -23,6 +23,8 @@
 from rest_framework import serializers
 from rest_framework.compat import postgres_fields, unicode_repr
 
+from .models import NestedForeignKeySource
+
 
 def dedent(blocktext):
     return '\n'.join([line[12:] for line in blocktext.splitlines()[1:-1]])
@@ -1164,6 +1166,25 @@ class Meta:
 
 
 class TestFieldSource(TestCase):
+    def test_traverse_nullable_fk(self):
+        """
+        A dotted source with nullable elements uses default when any item in the chain is None. #5849.
+
+        Similar to model example from test_serializer.py `test_default_for_multiple_dotted_source` method,
+        but using RelatedField, rather than CharField.
+        """
+        class TestSerializer(serializers.ModelSerializer):
+            target = serializers.PrimaryKeyRelatedField(
+                source='target.target', read_only=True, allow_null=True, default=None
+            )
+
+            class Meta:
+                model = NestedForeignKeySource
+                fields = ('target', )
+
+        model = NestedForeignKeySource.objects.create()
+        assert TestSerializer(model).data['target'] is None
+
     def test_named_field_source(self):
         class TestSerializer(serializers.ModelSerializer):