问题
I have been stuck for a while trying to set a dynamic CHIOCES in form selection using python 2.7. I need the CHOICES to come from the query in my def update_file_choices. Here is the code in views.py:
FILES_UPLOADED=[] ##choices varible for template
def update_file_choices(): ##setup choices for RoomForm in launch page
global FILES_UPLOADED
uploads = FileUpload.objects.all()
for file in uploads:
FILES_UPLOADED.append((file.title,file.title))
print 'FILES IN UPLOADS:', file
return(FILES_UPLOADED)
1. Forms from the following class work except they doesn't show titles of new files uploaded this session.
class RoomForm(forms.Form): ##for launch template
FILES_UPLOADED = update_file_choices()
titles = forms.ChoiceField(choices=FILES_UPLOADED)
2. So I changed to this version, calling the base class, but now the form sets up without any variable data.
class RoomForm(forms.Form):
def __init__(self, *args):
forms.Form.__init__(self, RoomForm)
FILES_UPLOADED = update_file_choices()
titles = forms.ChoiceField(choices=FILES_UPLOADED)
3. This had the same problem:
class RoomForm(forms.Form):
def __init__(self, *args, **kwargs):
super(RoomForm, self).__init__(*args, **kwargs)
FILES_UPLOADED = update_file_choices()
titles = forms.ChoiceField(choices=FILES_UPLOADED)
Any suggestions would be much appreciated.
回答1:
If your choices are coming directly from a queryset (of FileUpload), why don't you use the form field that is designed for that: ModelChoiceField?
titles = forms.ModelChoiceField(queryset=FileUpload.objects.all())
回答2:
You need to make it be some automatically changing iterable. Something like:
def files_uploaded():
for file in FileUpload.objects.all():
yield (file.title, file.title, )
class RoomForm(forms.Form):
titles = form.ChoiceField(choices=files_uploaded())
def __init__(self, *args, **kwargs):
super(RoomForm, self).__init__(*args, **kwargs)
self.fields['titles'].choices = files_uploaded()
来源:https://stackoverflow.com/questions/8933723/making-choices-in-forms-dynamic