Created
January 24, 2011 21:43
-
-
Save slacy/794021 to your computer and use it in GitHub Desktop.
Django Dynamic Form Choices
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
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