internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: carltongibson/django-filter

Issue:
tests fail version 0.11.0 debian/sid
```
python2 ./runtests.py
....................................ssss...s..x.ss..x..x.....................................s..........x..................xx...................E..............u.......x........................x................s..................s....sss.........
======================================================================
ERROR: test_filtering_uses_distinct (tests.test_filters.FilterTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/«PKGBUILDDIR»/tests/test_filters.py", line 192, in test_filtering_uses_distinct
    result = qs.distinct.assert_called_once()
  File "/usr/lib/python2.7/dist-packages/mock/mock.py", line 721, in __getattr__
    raise AttributeError(name)
AttributeError: assert_called_once

----------------------------------------------------------------------
Ran 245 tests in 0.386s

FAILED (errors=1, skipped=13, expected failures=8, unexpected successes=1)
Creating test database for alias 'default'...
Destroying test database for alias 'default'...
```



Discussion:
Curious. The CI build is passing.

Can you take a look at the Travis config and see where setup differs? 

What's your Python version etc?

I cannot see any reference to assert_called_once in https://docs.python.org/3/library/unittest.mock.html

Rather I see a function called to assert_called_once_with.

Am wondering if assert_called_once was an undocumented mock function that was removed in Python 3.4.3?

Your tests seem to be using 3.4.2

OK. That gives me something to go. I'll investigate. 

Thanks for the extra details 


Resolving patch:
diff --git a/django_filters/filters.py b/django_filters/filters.py
--- a/django_filters/filters.py
+++ b/django_filters/filters.py
@@ -84,9 +84,9 @@ def filter(self, qs, value):
             lookup = self.lookup_type
         if value in ([], (), {}, None, ''):
             return qs
-        qs = self.get_method(qs)(**{'%s__%s' % (self.name, lookup): value})
         if self.distinct:
             qs = qs.distinct()
+        qs = self.get_method(qs)(**{'%s__%s' % (self.name, lookup): value})
         return qs
 
 


Test patch:
diff --git a/tests/test_filters.py b/tests/test_filters.py
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -189,7 +189,7 @@ def test_filtering_uses_distinct(self):
         qs = mock.Mock(spec=['filter', 'distinct'])
         f = Filter(name='somefield', distinct=True)
         f.filter(qs, 'value')
-        result = qs.distinct.assert_called_once()
+        result = qs.distinct.assert_called_once_with()
         self.assertNotEqual(qs, result)
Repository: carltongibson/django-filter

Issue:
Update PyPI uploading.
Inline with maraujop/django-crispy-forms#460



Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -9,8 +9,14 @@
 version = '0.11.0'
 
 if sys.argv[-1] == 'publish':
-    os.system("python setup.py sdist upload")
-    os.system("python setup.py bdist_wheel upload")
+    if os.system("pip freeze | grep wheel"):
+        print("wheel not installed.\nUse `pip install wheel`.\nExiting.")
+        sys.exit()
+    if os.system("pip freeze | grep twine"):
+        print("twine not installed.\nUse `pip install twine`.\nExiting.")
+        sys.exit()
+    os.system("python setup.py sdist bdist_wheel")
+    os.system("twine upload dist/*")
     print("You probably want to also tag the version now:")
     print("  git tag -a %s -m 'version %s'" % (version, version))
     print("  git push --tags")


Test patch:
Repository: carltongibson/django-filter

Issue:
RangeWidget Bug
For example, I want to create simple date filter with HTML5 `<input type="date"...`:

```
created = django_filters.DateFromToRangeFilter(label="Date range",
        widget=RangeWidget(attrs={'type': 'date'}))
```

And that's have to be OK (https://github.com/alex/django-filter/blob/develop/django_filters/widgets.py#L82):

```
class RangeWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        widgets = (forms.TextInput(attrs=attrs), forms.TextInput(attrs=attrs))
        super(RangeWidget, self).__init__(widgets, attrs)
```

But django's `forms.widgets.TextInput.__init__` modificates attrs !(https://github.com/django/django/blob/master/django/forms/widgets.py#L271)

```
    def __init__(self, attrs=None):
        if attrs is not None:
            self.input_type = attrs.pop('type', self.input_type) # dict attrs CHANGED!
        super(TextInput, self).__init__(attrs)
```

So, the first widget would be `type="date"`, and second still will be `type="text"`.
The solution is to make a copy of `attrs`:

```
class RangeWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        widgets = (forms.TextInput(attrs=attrs.copy()), forms.TextInput(attrs=attrs.copy()))
        super(RangeWidget, self).__init__(widgets, attrs)
```



Discussion:

Resolving patch:
diff --git a/django_filters/widgets.py b/django_filters/widgets.py
--- a/django_filters/widgets.py
+++ b/django_filters/widgets.py
@@ -80,7 +80,7 @@ def option_string(self):
 
 class RangeWidget(forms.MultiWidget):
     def __init__(self, attrs=None):
-        widgets = (forms.TextInput(attrs=attrs), forms.TextInput(attrs=attrs))
+        widgets = (forms.TextInput, forms.TextInput)
         super(RangeWidget, self).__init__(widgets, attrs)
 
     def decompress(self, value):


Test patch:
diff --git a/tests/test_widgets.py b/tests/test_widgets.py
--- a/tests/test_widgets.py
+++ b/tests/test_widgets.py
@@ -136,6 +136,14 @@ def test_widget(self):
             -
             <input type="text" name="price_1" value="9.99" />""")
 
+    def test_widget_attributes(self):
+        w = RangeWidget(attrs={'type': 'date'})
+        self.assertEqual(len(w.widgets), 2)
+        self.assertHTMLEqual(w.render('date', ''), """
+            <input type="date" name="date_0" />
+            -
+            <input type="date" name="date_1" />""")
+
 
 class BooleanWidgetTests(TestCase):
     """
Repository: carltongibson/django-filter

Issue:
django_filters.widgets.BooleanWidget does not implement render
So it raises a `NotImplementedError` when django tries to render it. I see that django-filter doesn't use BooleanWidget but django restframework filters does for its BooleanField and it breaks the browsable API of django restframework.

I use:
Django==1.8.9
django-filter==0.12.0
djangorestframework==3.3.2
djangorestframework-filters==0.7.0



Discussion:

Resolving patch:
diff --git a/django_filters/widgets.py b/django_filters/widgets.py
--- a/django_filters/widgets.py
+++ b/django_filters/widgets.py
@@ -98,24 +98,42 @@ def decompress(self, value):
         return value
 
 
-class BooleanWidget(forms.Widget):
+class BooleanWidget(forms.Select):
     """Convert true/false values into the internal Python True/False.
     This can be used for AJAX queries that pass true/false from JavaScript's
     internal types through.
     """
-    def value_from_datadict(self, data, files, name):
-        """
-        """
-        value = super(BooleanWidget, self).value_from_datadict(
-            data, files, name)
+    def __init__(self, attrs=None):
+        choices = (('', _('Unknown')),
+                   ('true', _('Yes')),
+                   ('false', _('No')))
+        super(BooleanWidget, self).__init__(attrs, choices)
 
-        if value is not None:
-            if value.lower() == 'true':
-                value = True
-            elif value.lower() == 'false':
-                value = False
+    def render(self, name, value, attrs=None):
+        try:
+            value = {
+                True: 'true',
+                False: 'false',
+                '1': 'true',
+                '0': 'false'
+            }[value]
+        except KeyError:
+            value = ''
+        return super(BooleanWidget, self).render(name, value, attrs)
 
-        return value
+    def value_from_datadict(self, data, files, name):
+        value = data.get(name, None)
+        if isinstance(value, string_types):
+            value = value.lower()
+
+        return {
+            '1': True,
+            '0': False,
+            'true': True,
+            'false': False,
+            True: True,
+            False: False,
+        }.get(value, None)
 
 
 class CSVWidget(forms.TextInput):


Test patch:
diff --git a/tests/test_widgets.py b/tests/test_widgets.py
--- a/tests/test_widgets.py
+++ b/tests/test_widgets.py
@@ -149,6 +149,15 @@ def test_widget_attributes(self):
 class BooleanWidgetTests(TestCase):
     """
     """
+    def test_widget_render(self):
+        w = BooleanWidget()
+        self.assertHTMLEqual(w.render('price', ''), """
+            <select name="price">
+                <option selected="selected" value="">Unknown</option>
+                <option value="true">Yes</option>
+                <option value="false">No</option>
+            </select>""")
+
     def test_widget_value_from_datadict(self):
         """
         """
Repository: carltongibson/django-filter

Issue:
Add settings for help_text in Filter
Hello,

In refference to #292 and discusion in #136 I wrote patch to provide settings for help_text in Filter.

Unfortunately, my English doesn't allow me write any docs.

Greetings,



Discussion:

Resolving patch:
diff --git a/django_filters/filters.py b/django_filters/filters.py
--- a/django_filters/filters.py
+++ b/django_filters/filters.py
@@ -8,6 +8,7 @@
 from django.db.models import Q
 from django.db.models.sql.constants import QUERY_TERMS
 from django.db.models.constants import LOOKUP_SEP
+from django.conf import settings
 from django.utils import six
 from django.utils.timezone import now
 from django.utils.translation import ugettext_lazy as _
@@ -83,7 +84,13 @@ def field(self):
         if not hasattr(self, '_field'):
             help_text = self.extra.pop('help_text', None)
             if help_text is None:
-                help_text = _('This is an exclusion filter') if self.exclude else _('Filter')
+                if self.exclude and getattr(settings, "FILTERS_HELP_TEXT_EXCLUDE", True):
+                    help_text = _('This is an exclusion filter')
+                elif not self.exclude and getattr(settings, "FILTERS_HELP_TEXT_FILTER", True):
+                    help_text = _('Filter')
+                else:
+                    help_text = ''
+
             if (self.lookup_expr is None or
                     isinstance(self.lookup_expr, (list, tuple))):
 


Test patch:
diff --git a/tests/test_filters.py b/tests/test_filters.py
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -7,7 +7,7 @@
 import unittest
 
 from django import forms
-from django.test import TestCase
+from django.test import TestCase, override_settings
 
 from django_filters import filters
 from django_filters.fields import (
@@ -70,6 +70,20 @@ def test_field_with_exclusion(self):
         self.assertIsInstance(field, forms.Field)
         self.assertEqual(field.help_text, 'This is an exclusion filter')
 
+    @override_settings(FILTERS_HELP_TEXT_FILTER=False)
+    def test_default_field_settings(self):
+        f = Filter()
+        field = f.field
+        self.assertIsInstance(field, forms.Field)
+        self.assertEqual(field.help_text, '')
+
+    @override_settings(FILTERS_HELP_TEXT_EXCLUDE=False)
+    def test_field_with_exclusion_settings(self):
+        f = Filter(exclude=True)
+        field = f.field
+        self.assertIsInstance(field, forms.Field)
+        self.assertEqual(field.help_text, '')
+
     def test_field_with_single_lookup_expr(self):
         f = Filter(lookup_expr='iexact')
         field = f.field
Repository: carltongibson/django-filter

Issue:
Improve docs on common pitfalls
Referencing this [discussion](https://github.com/carltongibson/django-filter/issues/394#issuecomment-202942471), docs could better explain some common misunderstandings about filter validation and data shape for various query expressions. eg, a CharFilter validates and outputs a single string, which is incompatible with 'in' lookups as it expects a list of strings. 

[This](https://github.com/carltongibson/django-filter/blob/v0.13/docs/usage.txt#L82-L100) section would be a good spot to expand on it. 



Discussion:

Resolving patch:
diff --git a/docs/conf.py b/docs/conf.py
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -240,3 +240,15 @@
 
 # How to display URL addresses: 'footnote', 'no', or 'inline'.
 #texinfo_show_urls = 'footnote'
+
+
+# see:
+# https://github.com/snide/sphinx_rtd_theme#using-this-theme-locally-then-building-on-read-the-docs
+on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
+
+# only import and set the theme if we're building docs locally
+if not on_rtd:
+    import sphinx_rtd_theme
+
+    html_theme = 'sphinx_rtd_theme'
+    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]


Test patch:
Repository: carltongibson/django-filter

Issue:
Remove extra word in tips.txt



Discussion:

Resolving patch:
diff --git a/django_filters/compat.py b/django_filters/compat.py
--- a/django_filters/compat.py
+++ b/django_filters/compat.py
@@ -14,9 +14,11 @@
 is_crispy = 'crispy_forms' in settings.INSTALLED_APPS and crispy_forms
 
 
-# coreapi only compatible with DRF 3.4+
+# coreapi is optional (Note that uritemplate is a dependency of coreapi)
+# Fixes #525 - cannot simply import from rest_framework.compat, due to
+# import issues w/ django-guardian.
 try:
-    from rest_framework.compat import coreapi
+    import coreapi
 except ImportError:
     coreapi = None
 


Test patch:
Repository: carltongibson/django-filter

Issue:
Document (or change) `distinct=True` on default `MultipleChoiceFilter`
Looking to merge #217, we note it was necessary to have MultipleChoiceFilter default to `distinct=True` in order to preserve backwards compatibility. 

That's the norm. `distinct` is normally `False` by default, and is documented as such. 

Either change the code or document the exception. (Change the code is favourite, but make sure you call that out properly if/when you do it.)



Discussion:
The majority of to-many relationships need to be de-duplicated (which is only possible w/ distinct?). If we change this to false, the auto-generated to-many relationships will generally be rendered useless. Two possibilities:
- Leave it as is, documenting the exception (as stated above).
- Revert to the default, but explicitly set `distinct=True` when auto-generating to-many rels (and document this exception).

My original view was just to document it...

Although that's not what I said... 


Resolving patch:
diff --git a/django_filters/filters.py b/django_filters/filters.py
--- a/django_filters/filters.py
+++ b/django_filters/filters.py
@@ -246,8 +246,8 @@ class MultipleChoiceFilter(Filter):
     `is_noop` test. You can override `is_noop` if you need a different test
     for your application.
 
-    `distinct` defaults to `True` on this class to preserve backward
-    compatibility.
+    `distinct` defaults to `True` as to-many relationships will generally
+    require this.
     """
     field_class = forms.MultipleChoiceField
 


Test patch:
Repository: carltongibson/django-filter

Issue:
Import of rest_framework backend can fail
In the DRF docs, they give an example which looks like:

```
import django_filters
# ...

class ProductFilter(django_filters.rest_framework.FilterSet):
    # ...
```

This does not work, however, with the way the `django_filters/__init__.py` is set up. Using this example, I get:

`AttributeError: 'module' object has no attribute 'rest_framework'`

I have found a fix for it, by adding the following to `django_filters/__init__.py`:

`from . import rest_framework`


Discussion:
Yeah. That's probably right. Fancy doing a PR? 

Sure thing, I'll have it to you shortly.

There is a problem in that the `rest_framework` sub-package has a dependency on DRF. If DRF isn't installed, then `django_filters` will not be importable. 

One possible way to get around this is to add a `compat.rest_framework` check, and then only import the `rest_framework` sub-package if it passes.

Alternatively, the docs could be updated to include the correct import

``` py
import django_filters.rest_framework

class ProductFilter(django_filters.rest_framework.FilterSet):
    # ...
```

I think `import django_filters` is my preferred API. 

> One possible way to get around this is to add a compat.rest_framework check, and then only import the rest_framework sub-package if it passes.

Yes. This. 


Resolving patch:
diff --git a/django_filters/__init__.py b/django_filters/__init__.py
--- a/django_filters/__init__.py
+++ b/django_filters/__init__.py
@@ -4,6 +4,13 @@
 from .filterset import FilterSet
 from .filters import *
 
+# We make the `rest_framework` module available without an additional import.
+#   If DRF is not installed we simply set None.
+try:
+    from . import rest_framework
+except ImportError:
+    rest_framework = None
+
 __version__ = '1.0.0'
 
 


Test patch:
Repository: carltongibson/django-filter

Issue:
Impossible to overwrite filter attributes in child class
Maybe we are missing something, but why does this happen?

```
class FooBaseFilter(django_filters.FilterSet):
    key = django_filters.CharFilter(label='code')
    name = django_filters.CharFilter(label='name')

class FooFilter1(FooBaseFilter):
    pass

class FooFilter2(FooBaseFilter):
    key = None
```

Expected result:

* rendering a FooFilter1 does show a filter on key.
* rendering a FooFilter2 does not show a filter on key.

Result:

* both FooTable2 and FooTable2 show a filter key.

Are we doing something wrong? Is this a bug or just very unpythonic? Feedback welcome.




Discussion:
This doesn't seem unreasonable. A quick test shows that Django's forms support this behavior, although DRF's serializers do not. 

Resolving patch:
diff --git a/django_filters/filterset.py b/django_filters/filterset.py
--- a/django_filters/filterset.py
+++ b/django_filters/filterset.py
@@ -104,7 +104,11 @@ def get_declared_filters(cls, bases, attrs):
         # merge declared filters from base classes
         for base in reversed(bases):
             if hasattr(base, 'declared_filters'):
-                filters = list(base.declared_filters.items()) + filters
+                filters = [
+                    (name, f) for name, f
+                    in base.declared_filters.items()
+                    if name not in attrs
+                ] + filters
 
         return OrderedDict(filters)
 


Test patch:
diff --git a/tests/test_filterset.py b/tests/test_filterset.py
--- a/tests/test_filterset.py
+++ b/tests/test_filterset.py
@@ -571,6 +571,21 @@ class Meta:
             list(F.base_filters) + ['amount_saved'],
             list(FtiF.base_filters))
 
+    def test_declared_filter_disabling(self):
+        class Parent(FilterSet):
+            f1 = CharFilter()
+            f2 = CharFilter()
+
+        class Child(Parent):
+            f1 = None
+
+        class Grandchild(Child):
+            pass
+
+        self.assertEqual(len(Parent.base_filters), 2)
+        self.assertEqual(len(Child.base_filters), 1)
+        self.assertEqual(len(Grandchild.base_filters), 1)
+
 
 class FilterSetInstantiationTests(TestCase):
Repository: carltongibson/django-filter

Issue:
HiddenWidget for OrderingField result in empty result with bizarre default value
I defined an OrderingFilter with HiddenInput and when displaying this field once the form has been submitted, the field render as `<input id="id_o" name="o" type="hidden" value="[]">`

Which is problematic because when submitted once again, there won't be any result due to this default value of `[]`.

I believe this is due to the `BaseCSVWidget.value_from_datadict` method that does a little too much on the value:
```
class BaseCSVWidget(forms.Widget):
    def value_from_datadict(self, data, files, name):
        value = super(BaseCSVWidget, self).value_from_datadict(data, files, name)

        if value is not None:
            if value == '':  # empty value should parse as an empty list
                return []
            return value.split(',')
        return None
```

And here is my filterset for reference:
```
class DocumentListFilter(django_filters.FilterSet):
    text = django_filters.CharFilter(method='filter_text')

    # Ordering
    o = OrderingFilter(
        widget=forms.HiddenInput,
        fields=(
            ('indice', 'indice'),
            ('weight', 'weight'),
        ),
    )
```
Fix CSV rendering for empty list. 
Fixes #615

* [x] Test Demonstrates issue with `render` for #615 
* [ ] Fix `render`


Discussion:
`value_from_datadict` is not involved in rendering the widget. (It comes in when handing the GET parameter pulled from the query string.)

If you could produce a failing case for [`CSVWidgetTests`](https://github.com/carltongibson/django-filter/blob/develop/tests/test_widgets.py#L177-L197) that would help. 

I'm wondering if you don't need to create a `HiddenCSVWiget` subclass, in parallel to `CSVWidget`


Added a pull request with the test. When debugging, I found out that `value_from_datadict` is called twice, once for retrieving the value for the _clean\_*_ process and a second time for the default value when rendering the field.


Resolving patch:
diff --git a/django_filters/widgets.py b/django_filters/widgets.py
--- a/django_filters/widgets.py
+++ b/django_filters/widgets.py
@@ -167,7 +167,7 @@ def render(self, name, value, attrs=None):
 
         if len(value) <= 1:
             # delegate to main widget (Select, etc...) if not multiple values
-            value = value[0] if value else value
+            value = value[0] if value else ''
             return super(BaseCSVWidget, self).render(name, value, attrs)
 
         # if we have multiple values, we need to force render as a text input


Test patch:
diff --git a/tests/test_widgets.py b/tests/test_widgets.py
--- a/tests/test_widgets.py
+++ b/tests/test_widgets.py
@@ -183,6 +183,9 @@ def test_widget(self):
         self.assertHTMLEqual(w.render('price', ''), """
             <input type="text" name="price" />""")
 
+        self.assertHTMLEqual(w.render('price', []), """
+            <input type="text" name="price" />""")
+
         self.assertHTMLEqual(w.render('price', '1'), """
             <input type="text" name="price" value="1" />""")
Repository: carltongibson/django-filter

Issue:
DeprecationWarning on python 3.7
```
django_filters/widgets.py:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
```

see potential fix here: https://github.com/pyparsing/pyparsing/pull/16/files


Discussion:
Actually since Python 2 support was dropped the fix can be simpler.

Resolving patch:
diff --git a/django_filters/widgets.py b/django_filters/widgets.py
--- a/django_filters/widgets.py
+++ b/django_filters/widgets.py
@@ -1,4 +1,4 @@
-from collections import Iterable
+from collections.abc import Iterable
 from itertools import chain
 from re import search, sub
 


Test patch: