Skip to content
Using an object for Django's ChoiceField choices

Using an object for Django's ChoiceField choices

March 29, 2009

I had another thought about per-instance choices for forms.ChoiceField. Instead of overriding the __init__ method of your form class, you could use an object with an __iter__ method that returns a fresh iterable each time it is called.

from django import forms


class LetterChoices(object):
    """Return a random list of max_choices letters of the alphabet."""
    def __init__(self, max_choices=3):
        self.max_choices = max_choices

    def __iter__(self):
        import string, random

        return iter((l, l) for l in random.sample(string.ascii_uppercase, self.max_choices))


class LetterForm(forms.Form):
    """Pick a letter from a small, random set."""
    letter = forms.ChoiceField(choices=LetterChoices())

I don’t know if I prefer that style to having a simple function - having to instantiate the class seems wrong to me, I’d much rather use any callable as the choices argument.

Last updated on