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

Issue:
Schemas Generator  produces error for views with no pagination class.
## 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

```
Class TaskList(generics.ListCreateAPIView):
    queryset =  TaskModel.objects.all()
    serializer_class = TaskSerializer
    pagination_class = None


class ApiDocView(APIView):

    def get(self, request, format=None):
        generator = schemas.SchemaGenerator(title='API')
        return Response(generator.get_schema(request=request))
```
## Expected behavior

Schema generator should consider views with pagination_class = None. 
This issue is similar to #4265
## Actual behavior

Schema generator gives error
 File "/path/to/env/local/lib/python2.7/site-packages/rest_framework/schemas.py", line 284, in get_pagination_fields
    paginator = view.pagination_class()
TypeError: 'NoneType' object is not callable



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
@@ -278,7 +278,7 @@ def get_pagination_fields(self, path, method, callback, view):
         if hasattr(callback, 'actions') and ('list' not in callback.actions.values()):
             return []
 
-        if not hasattr(view, 'pagination_class'):
+        if not getattr(view, 'pagination_class', None):
             return []
 
         paginator = view.pagination_class()


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

Issue:
SchemaGenerator: 'FooViewSet' object has no attribute 'format_kwarg'
## 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

Using the new schema generation via `DefaultRouter`, hook a `ViewSet` into it.
## Expected behavior

A schema is generated for the `ViewSet`.
## Actual behavior

`AttributeError: 'AddressViewSet' object has no attribute 'format_kwarg'`



Discussion:
I managed to avoid #4265 and #4278 but then ran into this.


Resolving patch:
diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -84,6 +84,7 @@ def get_schema(self, request=None):
                 method = link.action.upper()
                 view = callback.cls()
                 view.request = clone_request(request, method)
+                view.format_kwarg = None
                 try:
                     view.check_permissions(view.request)
                 except exceptions.APIException:


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

Issue:
default=CurrentUserDefault and read_only=True in DRF 3.4.0 broken if unique_together is being used in a Model for a ModelSerializer
## 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

``` python
import django
django.setup()
from django.contrib.auth import get_user_model
from django.db import models
from django.conf import settings
from rest_framework import serializers, test


class Item(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    item_number = models.IntegerField()

    class Meta:
       unique_together = (('user', 'item_number'),)


class ItemSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True,
                                              default=serializers.CurrentUserDefault())
    class Meta:
        model = Item
        fields = ('id', 'item_number', 'user')


User = get_user_model()
user = User.objects.create_user(username='asdf')
request = test.APIRequestFactory().post('/')
request.user = user

item = Item.objects.create(user=user, item_number=3)

data = {'item_number': item.item_number}

context = {'request': request}

serializer = ItemSerializer(data=data, context=context)

assert not serializer.is_valid(), 'Should be False!'

```
## Expected behavior

The serializer should not be valid. This is the case using djangorestframework == 3.3.0
## Actual behavior

The serializer is valid. This is the case using djangorestframework == 3.4.0

I've tracked the root of the issue and it seems to be pull request #4192, where a new condition is added to `get_unique_together_validators()`: "`and not field.read_only`"



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
@@ -1396,9 +1396,8 @@ def get_unique_together_validators(self):
         # cannot map to a field, and must be a traversal, so we're not
         # including those.
         field_names = {
-            field.source for field in self.fields.values()
+            field.source for field in self._writable_fields
             if (field.source != '*') and ('.' not in field.source)
-            and not field.read_only
         }
 
         # Note that we make sure to check `unique_together` both on the


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

Issue:
Allow configuration of DefaultRouter's root view renderer classes
Currently, we can set the schema_renderer classes as kwargs on the DefaultRouter, but can't override the renderer classes used on the root view which comes from the settings. 

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

It would be desirable to replace BrowsableAPI renderer with the SwaggerUI html renderer in Django REST Swagger.

Referencing issue:
https://github.com/marcgibbons/django-rest-swagger/issues/479#issuecomment-232998716



Discussion:
Thanks Marc. Getting back onto the project after DjangoCon - apologies for the delay.


Resolving patch:
diff --git a/rest_framework/routers.py b/rest_framework/routers.py
--- a/rest_framework/routers.py
+++ b/rest_framework/routers.py
@@ -283,6 +283,10 @@ def __init__(self, *args, **kwargs):
         self.schema_title = kwargs.pop('schema_title', None)
         self.schema_url = kwargs.pop('schema_url', None)
         self.schema_renderers = kwargs.pop('schema_renderers', self.default_schema_renderers)
+        if 'root_renderers' in kwargs:
+            self.root_renderers = kwargs.pop('root_renderers')
+        else:
+            self.root_renderers = list(api_settings.DEFAULT_RENDERER_CLASSES)
         super(DefaultRouter, self).__init__(*args, **kwargs)
 
     def get_api_root_view(self, api_urls=None):
@@ -294,7 +298,7 @@ def get_api_root_view(self, api_urls=None):
         for prefix, viewset, basename in self.registry:
             api_root_dict[prefix] = list_name.format(basename=basename)
 
-        view_renderers = list(api_settings.DEFAULT_RENDERER_CLASSES)
+        view_renderers = list(self.root_renderers)
         schema_media_types = []
 
         if api_urls and self.schema_title:


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

Issue:
Possible exception during validation of IPAddressField
I faced with not expected behaviour of IPAddress field during validation certain types of input.
## 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 serializer with IPAddressField
2. Pass not iterable object as input for the serializer. E.g. integer.
## Expected behavior

Validation error with usual text:
`['Enter a valid IPv4 or IPv6 address.']`
## Actual behavior

Exception:

```
rest_framework/fields.py:701: in run_validation
    return super(CharField, self).run_validation(data)
rest_framework/fields.py:487: in run_validation
    value = self.to_internal_value(data)
rest_framework/fields.py:807: in to_internal_value
    if data and ':' in data:
E   TypeError: argument of type 'int' is not iterable
```



Discussion:
Yup, looks valid, given your test case.


Resolving patch:
diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -804,7 +804,10 @@ def __init__(self, protocol='both', **kwargs):
         self.validators.extend(validators)
 
     def to_internal_value(self, data):
-        if data and ':' in data:
+        if not isinstance(data, six.string_types):
+            self.fail('invalid', value=data)
+
+        if ':' in data:
             try:
                 if self.protocol in ('both', 'ipv6'):
                     return clean_ipv6_address(data, self.unpack_ipv4)


Test patch:
diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -663,6 +663,7 @@ class TestIPAddressField(FieldValues):
         '127.122.111.2231': ['Enter a valid IPv4 or IPv6 address.'],
         '2001:::9652': ['Enter a valid IPv4 or IPv6 address.'],
         '2001:0db8:85a3:0042:1000:8a2e:0370:73341': ['Enter a valid IPv4 or IPv6 address.'],
+        1000: ['Enter a valid IPv4 or IPv6 address.'],
     }
     outputs = {}
     field = serializers.IPAddressField()
Repository: encode/django-rest-framework

Issue:
Always defer to explicit overrides.
Some of these may already be covered, but we should make sure that all the following are satisfied:
- If a user declares a field explicitly, but also includes it in `extra_kwargs` then warn/error.
- If a user declares a field explicitly, but also includes it in `read_only_fields` then warn/error.
- Don't allow `get_uniqueness_extra_kwargs` to override a declared field.
- Don't allow `get_uniqueness_extra_kwargs` to override a flag that has been set in `extra_kwargs`.
- If a serializer field has a `default`, then ensure that uniqueness validators use that for empty, rather than forcing `required=True` 



Discussion:
> - Don't allow get_uniqueness_extra_kwargs to override a declared field.

This already happens, a declared field will not be re-declared with new args.

> - If a serializer field has a default, then ensure that uniqueness validators use that for empty, rather than forcing required=True

A default of None on a declared field will work for uniqueness validation.

Thanks for those confirmations @gcbirzan!


Resolving patch:
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1324,9 +1324,8 @@ def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs
         # Update `extra_kwargs` with any new options.
         for key, value in uniqueness_extra_kwargs.items():
             if key in extra_kwargs:
-                extra_kwargs[key].update(value)
-            else:
-                extra_kwargs[key] = value
+                value.update(extra_kwargs[key])
+            extra_kwargs[key] = value
 
         return extra_kwargs, hidden_fields
 


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
@@ -976,3 +976,22 @@ class Meta:
         source = OneToOneSourceTestModel(target=target)
         serializer = ExampleSerializer(source)
         self.assertEqual(serializer.data, {'target': 1})
+
+
+class TestUniquenessOverride(TestCase):
+    def test_required_not_overwritten(self):
+        class TestModel(models.Model):
+            field_1 = models.IntegerField(null=True)
+            field_2 = models.IntegerField()
+
+            class Meta:
+                unique_together = (('field_1', 'field_2'),)
+
+        class TestSerializer(serializers.ModelSerializer):
+            class Meta:
+                model = TestModel
+                extra_kwargs = {'field_1': {'required': False}}
+
+        fields = TestSerializer().fields
+        self.assertFalse(fields['field_1'].required)
+        self.assertTrue(fields['field_2'].required)
Repository: encode/django-rest-framework

Issue:
Improve relation choices limiting (using html_cutoff)
When we're showing the HTML form field for related objects and we're trying to generate the choices for the select field, it doesn't seem to make sense to grab every single record in a table, only to display `html_cutoff` (default: 1000) of them and completely ignore the rest.

Instead, we should limit the number of objects we want from the database to the number of objects we're planning on displaying. This changeset makes the semantics of retrieving related objects the same as for displaying related objects. In other words, we limit the queryset to the first `html_cutoff` objects. That way we aren't pulling back more objects than necessary, because this can kill performance for tables with "lots" of records (~500k in my case, [~400k for others](https://github.com/tomchristie/django-rest-framework/issues/3329#issue-103045398)).

Closes #3329.



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
@@ -156,14 +156,16 @@ def get_attribute(self, instance):
         # Standard case, return the object instance.
         return get_attribute(instance, self.source_attrs)
 
-    @property
-    def choices(self):
+    def get_choices(self, cutoff=None):
         queryset = self.get_queryset()
         if queryset is None:
             # Ensure that field.choices returns something sensible
             # even when accessed with a read-only field.
             return {}
 
+        if cutoff is not None:
+            queryset = queryset[:cutoff]
+
         return OrderedDict([
             (
                 six.text_type(self.to_representation(item)),
@@ -172,13 +174,17 @@ def choices(self):
             for item in queryset
         ])
 
+    @property
+    def choices(self):
+        return self.get_choices()
+
     @property
     def grouped_choices(self):
         return self.choices
 
     def iter_options(self):
         return iter_options(
-            self.grouped_choices,
+            self.get_choices(cutoff=self.html_cutoff),
             cutoff=self.html_cutoff,
             cutoff_text=self.html_cutoff_text
         )
@@ -487,9 +493,12 @@ def to_representation(self, iterable):
             for value in iterable
         ]
 
+    def get_choices(self, cutoff=None):
+        return self.child_relation.get_choices(cutoff)
+
     @property
     def choices(self):
-        return self.child_relation.choices
+        return self.get_choices()
 
     @property
     def grouped_choices(self):
@@ -497,7 +506,7 @@ def grouped_choices(self):
 
     def iter_options(self):
         return iter_options(
-            self.grouped_choices,
+            self.get_choices(cutoff=self.html_cutoff),
             cutoff=self.html_cutoff,
             cutoff_text=self.html_cutoff_text
         )


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

Issue:
@choices representation of RelatedField
can we change
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/relations.py#L154

from

```
    return OrderedDict([
        (
            six.text_type(self.to_representation(item)),
            self.display_value(item)
        )
        for item in queryset
```

to

```
    return OrderedDict([
        (
            force_text(self.to_representation(item), strings_only=True),
            self.display_value(item)
        )
        for item in queryset
```

????

When i make OPTION request, i've got metada for related field choices of action:
1st case:

{display_name: "Acura", value: "184"} (this is wrong)

2nd case:

{display_name: "Acura", value: 184} (it's ok)

Here we got  field.choices:

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

```
        field_info['choices'] = [
            {
                'value': choice_value,
                'display_name': force_text(choice_name, strings_only=True)
            }
            for choice_value, choice_name in field.choices.items()
```

value is always string now.



Discussion:
Yup, that seems like a valid request to me.
We no longer display relational choices in `OPTIONS` by default, but the underlying change here is still reasonable & correct.


Resolving patch:
diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -168,7 +168,7 @@ def get_choices(self, cutoff=None):
 
         return OrderedDict([
             (
-                six.text_type(self.to_representation(item)),
+                self.to_representation(item),
                 self.display_value(item)
             )
             for item in 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
@@ -614,7 +614,7 @@ class Meta:
                 fields = '__all__'
 
         serializer = TestSerializer()
-        expected = OrderedDict([('1', 'Red Color'), ('2', 'Yellow Color'), ('3', 'Green Color')])
+        expected = OrderedDict([(1, 'Red Color'), (2, 'Yellow Color'), (3, 'Green Color')])
         self.assertEqual(serializer.fields['color'].choices, expected)
 
     def test_custom_display_value(self):
@@ -630,7 +630,7 @@ class Meta:
                 fields = '__all__'
 
         serializer = TestSerializer()
-        expected = OrderedDict([('1', 'My Red Color'), ('2', 'My Yellow Color'), ('3', 'My Green Color')])
+        expected = OrderedDict([(1, 'My Red Color'), (2, 'My Yellow Color'), (3, 'My Green Color')])
         self.assertEqual(serializer.fields['color'].choices, expected)
Repository: encode/django-rest-framework

Issue:
'ViewSet' object has no attribute 'action' during Schema generation
## Steps to reproduce

Create a `ModelViewSet` that uses `get_serializer_class()`:

``` python
class MyViewSet(viewsets.ModelViewSet):
    queryset = Person.objects.all()

    def get_serializer_class(self):
        if self.action == 'list':
            return serializers.SerializerB
        return serializers.SerializerA
```
## Expected behavior

Schema should be generated in a view that uses the `CoreJSONRenderer`.
## Actual behavior

An `AttributeError` is thrown: `'MyViewSet' object has no attribute 'action'`.

This is related to #4373 and #4278. If this isn't a bug, I may be missing something...the docs do have this method as the suggested way to dynamically change serializers.

Using djangorestframework==3.4.4 and python2.7.



Discussion:
Yup, makes sense. Thanks for raising this.


Resolving patch:
diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -79,6 +79,13 @@ def get_schema(self, request=None):
             view.kwargs = {}
             view.format_kwarg = None
 
+            actions = getattr(callback, 'actions', None)
+            if actions is not None:
+                if method == 'OPTIONS':
+                    view.action = 'metadata'
+                else:
+                    view.action = actions.get(method.lower())
+
             if request is not None:
                 view.request = clone_request(request, method)
                 try:


Test patch:
diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -49,6 +49,7 @@ def custom_list_action(self, request):
 
     def get_serializer(self, *args, **kwargs):
         assert self.request
+        assert self.action
         return super(ExampleViewSet, self).get_serializer(*args, **kwargs)