Skip to content

Instantly share code, notes, and snippets.

@joshdavies89
Last active July 20, 2020 09:03
Show Gist options
  • Select an option

  • Save joshdavies89/33028fadb59f2eefc9a280798986a31e to your computer and use it in GitHub Desktop.

Select an option

Save joshdavies89/33028fadb59f2eefc9a280798986a31e to your computer and use it in GitHub Desktop.
Filter list choices - Django
## Filter choices examples below function.
@classmethod
def filter_choices(self, passed_choices):
'''
Filter choices, user for ChoiceField etc.
'''
result = []
for reason in passed_choices:
for item in self.REASON_CHOICES:
if item[0] == reason:
result.append(item)
return result
REASON_CHOICES = [
(CHOICE_ONE, _ ('Choice one')),
(CHOICE_TWO, _ ('Choice two')),
(CHOICE_THREE, _ ('Choice three')),
(CHOICE_FOUR, _ ('Choice four')),
]
FILTERED_CHOICES = [
CHOICE_ONE,
CHOICE_TWO,
]
MORE_FILTERED_CHOICES = [
CHOICE_THREE,
CHOICE_FOUR,
]
## Usage
field = forms.ChoiceField(choices=filter_choices(FILTERED_CHOICES))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment