我的form.py中有一个表单,如下所示:
- from django import forms
- class ItemList(forms.Form):
- item_list = forms.ChoiceField()
我需要使用数据库中的某些数据填充item_list.当在HTML item_list中生成时应该是这样的:
- <select title="ItemList">
- <option value="1">Select Item 1</option>
- <option value="2">Select Item 2</option>
- </select>
解决方法
看看Django文档中的这个例子:
> http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#a-full-example
基本上,您可以使用Field对象上的queryset关键字参数来从数据库中抓取行:
- class BookForm(forms.Form):
- authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
更新
如果您需要动态模型选择字段,则可以在表单的构造函数中移交您的项目ID,并相应调整查询器:
- class ItemForm(forms.Form):
- # here we use a dummy `queryset`,because ModelChoiceField
- # requires some queryset
- item_field = forms.ModelChoiceField(queryset=Item.objects.none())
- def __init__(self,item_id):
- super(ItemForm,self).__init__()
- self.fields['item_field'].queryset = Item.objects.filter(id=item_id)
附:我没有测试这个代码,我不知道你的确切设置,但我希望主要的想法.
资源:
> http://www.mail-archive.com/django-users@googlegroups.com/msg48058.html
> http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField