Skip to content

Commit

Permalink
Backport: Fixed setting callable choices on Django <5.0. (carltongibs…
Browse files Browse the repository at this point in the history
…on#1648)

* Failing test for ChoiceField eagerly evaluating choices
* Fixed regression in choices setter for Django 4.2.

---------

Co-authored-by: Carlton Gibson <[email protected]>
  • Loading branch information
craigds and carltongibson committed Aug 19, 2024
1 parent 00e8865 commit d44f5fc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
8 changes: 4 additions & 4 deletions django_filters/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,13 +275,13 @@ def choices(self):
def choices(self, value):
if DJANGO_50:
value = self.iterator(self, value)
# Simple `super()` syntax for calling a parent property setter is
# unsupported. See https://github.com/python/cpython/issues/59170
super(ChoiceIteratorMixin, self.__class__).choices.__set__(self, value)
else:
super()._set_choices(value)
value = self.iterator(self, self._choices)

# Simple `super()` syntax for calling a parent property setter is
# unsupported. See https://github.com/python/cpython/issues/59170
super(ChoiceIteratorMixin, self.__class__).choices.__set__(self, value)
self._choices = self.widget.choices = value


# Unlike their Model* counterparts, forms.ChoiceField and forms.MultipleChoiceField do not set empty_label
Expand Down
9 changes: 9 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from django_filters.fields import (
BaseCSVField,
BaseRangeField,
ChoiceField,
DateRangeField,
DateTimeRangeField,
IsoDateTimeField,
Expand Down Expand Up @@ -58,6 +59,14 @@ def test_clean(self):
self.assertIsNone(f.clean([]))


class ChoiceFieldTests(TestCase):
def test_callable_choices_is_lazy(self):
def choices():
self.fail("choices should not be called during initialization")

ChoiceField(choices=choices)


class DateRangeFieldTests(TestCase):
def test_field(self):
f = DateRangeField()
Expand Down

0 comments on commit d44f5fc

Please sign in to comment.