使选择形式动态 [英] Making CHOICES in forms dynamic
本文介绍了使选择形式动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经被卡住了一段时间,试图使用python 2.7在表单选择中设置动态CHIOCES。我需要选择来自我的 def update_file_choices
中的查询。以下是views.py中的代码:
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。以下课程的表单工作,但不显示上传本课程的新文件的标题。
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。所以我改为这个版本,调用基类,但现在表单设置没有任何变量数据。
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。这有同样的问题:
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.
推荐答案
如果您的选择直接来自一个queryset( FileUpload
)的查询,那么为什么不使用为此设计的表单字段: ModelChoiceField
?
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())
这篇关于使选择形式动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文