Making CHOICES in forms dynamic

跟風遠走 提交于 2019-12-12 02:34:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!