Getting dynamic model choices in newforms

This is an excerpt from the form code used on this site; the tricky bit here is making the choices for the language field get filled in dynamically from Language.objects.all() on each form instantiation, so that new languages can be picked up automatically. It also adds a blank choice at the beginning so that users can't accidentally ignore the field and incorrectly end up with whatever Language was first in the list.

If you use this, always remember that you have to call the superclass __init__before you set your dynamic choices, and that you need to accept *args and **kwargs so you can pass them to it.

In theory, ModelChoiceField will solve this, but it still seems to be a bit buggy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

fromdjangoimportnewformsasformsfrommodelsimportLanguage# I put this on all required fields, because it's easier to pick up# on them with CSS or JavaScript if they have a class of "required"# in the HTML. Your mileage may vary.attrs_dict={'class':'required'}classAddSnippetForm(forms.Form):""" Form used for adding Snippets. """def__init__(self,*args,**kwargs):super(AddSnippetForm,self).__init__(*args,**kwargs)self.fields['language'].choices=[('','----------')]+[(lang.id,lang.name)forlanginLanguage.objects.all()]title=forms.CharField(max_length=250,widget=forms.TextInput(attrs=attrs_dict))description=forms.CharField(widget=forms.Textarea(attrs=attrs_dict))code=forms.CharField(widget=forms.Textarea(attrs=attrs_dict))tag_list=forms.CharField(max_length=250,widget=forms.TextInput(attrs=attrs_dict))language=forms.ChoiceField(choices=(),widget=forms.Select(attrs=attrs_dict))

after
self.fields['language'].choices =
i put
'myfunction()'
, returning a list of choices and between '' because it is defined in another python file.
i got the following error at execution time:
need more than 1 value to unpack
What does it mean ???
Thank you very much
max