Skip to content

Commit

Permalink
Fix EnumFieldMixin.get_choices for enum34 1.1
Browse files Browse the repository at this point in the history
On Python 2 with enum34 version 1.1.0 or newer, an enum item with zero
value will evaluate to false.  This makes `get_choices` return incorrect
data for the zero item.  Fix this by doing the checking if a choice is
an enum value with `if isinstance(i, Enum)` rather than with `if i`.

Add a test case that checks the choices are correct.
  • Loading branch information
suutari-ai committed Dec 18, 2015
1 parent dc7ffd8 commit 7ec7d61
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion enumfields/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
# Force enum fields' options to use the `value` of the enumeration
# member as the `value` of SelectFields and similar.
return [
(i.value if i else i, display)
(i.value if isinstance(i, Enum) else i, display)
for (i, display)
in super(EnumFieldMixin, self).get_choices(include_blank, blank_choice)
]
Expand Down
2 changes: 2 additions & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,5 @@ class IntegerEnum(IntEnum):

zero_field = EnumIntegerField(ZeroEnum, null=True, default=None, blank=True)
int_enum = EnumIntegerField(IntegerEnum, null=True, default=None, blank=True)

zero2 = EnumIntegerField(ZeroEnum, default=ZeroEnum.ZERO)
3 changes: 2 additions & 1 deletion tests/test_django_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ def test_model_admin(superuser_client):
'color': MyModel.Color.RED.value,
'taste': MyModel.Taste.UMAMI.value,
'taste_int': MyModel.Taste.SWEET.value,
'random_code': secret_uuid
'random_code': secret_uuid,
'zero2': MyModel.ZeroEnum.ZERO.value,
}
response = superuser_client.post(url, follow=True, data=post_data)
response.render()
Expand Down
7 changes: 6 additions & 1 deletion tests/test_form_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

def get_form(**kwargs):
instance = MyModel(color=MyModel.Color.RED)
FormClass = modelform_factory(MyModel, fields=("color",))
FormClass = modelform_factory(MyModel, fields=("color", "zero2"))
return FormClass(instance=instance, **kwargs)


Expand All @@ -22,3 +22,8 @@ def test_unbound_form_with_instance():
def test_bound_form_with_instance():
form = get_form(data={"color": "g"})
assert 'value="g" selected="selected"' in six.text_type(form["color"])


def test_choices():
form = get_form()
assert form.base_fields["zero2"].choices == [(0, 'ZERO'), (1, 'ONE')]

0 comments on commit 7ec7d61

Please sign in to comment.