Last active
July 20, 2020 09:03
-
-
Save joshdavies89/33028fadb59f2eefc9a280798986a31e to your computer and use it in GitHub Desktop.
Filter list choices - Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## 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