Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incompatibility with django-filter #95

Open
kmmbvnr opened this issue Jan 29, 2019 · 1 comment
Open

Incompatibility with django-filter #95

kmmbvnr opened this issue Jan 29, 2019 · 1 comment
Labels

Comments

@kmmbvnr
Copy link

kmmbvnr commented Jan 29, 2019

It seems default django-enumfields form field rendering is incompatible with django-filters

class Color(Enum):
    RED = 'r'
    GREEN = 'g'
    BLUE = 'b'


class MyModel(models.Model):
    name1 = models.CharField(max_length=250)
    name2 = models.CharField(max_length=250)
    color = EnumField(Color, max_length=1)

class MyModelFilterSet(FilterSet):
    class Meta:
        model = MyModel
        fields = [ 'color']

This code cause to render following filter

<select name="color" id="id_color">
  <option value="" selected="">---------</option>
  <option value="Color.RED">RED</option>
  <option value="Color.GREEN">GREEN</option>
  <option value="Color.BLUE">BLUE</option>
</select>

Wich leads to

'Color.RED' is not a valid Color

@akx akx added the bug label Jan 16, 2020
@johanneswindelen
Copy link

johanneswindelen commented May 24, 2022

I ran into this problem and am working around it by subclassing ChoiceFilter and building the list of choices manually.

This assumes your enum values are of type int, though something similar should work for other types.

# filters.py
import django_filters as filters
from django import forms
from somewhere import YourEnum

class EnumChoiceFilter(filters.ChoiceFilter):
    field_class = forms.TypedChoiceField
    def __init__(self, enum_type, *args, **kwargs):
        empty_choice = [(None, "------")]
        choices =  [(v.value, v.name) for v in enum_type]
        kwargs.update({"choices": empty_choice + choices, "required": False, "coerce": int})
        super().__init__(*args, **kwargs)

class YourEnumFilter(filters.FilterSet):
    some_field = EnumChoiceFilter(YourEnum)
    ...

Until a better fix is available, this might work for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants