Skip to content

Instantly share code, notes, and snippets.

@slacy
Created January 24, 2011 21:43
Show Gist options
  • Save slacy/794021 to your computer and use it in GitHub Desktop.
Save slacy/794021 to your computer and use it in GitHub Desktop.
Django Dynamic Form Choices
class CreateItemForm(forms.Form):
categories = forms.MultipleChoiceField(
# Must fill in choices and initial from the DB at runtime
widget=forms.CheckboxSelectMultiple(),
required=False,
)
def __init__(self, *args, **kwargs):
user = kwargs['user']
del kwargs['user']
super(CreateItemForm, self).__init__(*args, **kwargs)
# Get all the possible categories, you could use info from *args, **kwargs
# here to filter the list of categories if you wanted. (i.e. to ones that
# are available to this user, etc.)
all_categories = Category.objects.order_by('name')
self.fields['categories'].choices = (
[(c.id, c.name) for c in all_categories])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment