在视图中使用数据库中的数据填充Django表单 [英] Populate a django form with data from database in view
问题描述
我的form.py中有一个看起来像这样的表单:
I have a form in my forms.py that looks like this:
from django import forms
class ItemList(forms.Form):
item_list = forms.ChoiceField()
我需要用数据库中的一些数据填充item_list。在HTML中生成时,item_list应该类似于:
I need to populate the item_list with some data from the database. When generated in HTML item_list should be something like:
<select title="ItemList">
<option value="1">Select Item 1</option>
<option value="2">Select Item 2</option>
</select>
我的select语句中的选项值几乎每次都会更改,因为查询中的变量经常更改生成新结果。
The options values in my select statement will change almost every time since a variable in the query will often change generating new results.
我需要在view.py和模板文件中放入哪些内容,以便使用数据库中的值填充ItemList?
What do I need to put in the view.py and also in my template files to populate the ItemList with values from the database?
推荐答案
在Django文档中查看以下示例:
Take a look at this example in the Django documentation:
- http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#a-full-example
,您可以在Field对象上使用 queryset
关键字参数,从数据库中获取行:
Basically, you can use the queryset
keyword argument on a Field object, to grab rows from your database:
class BookForm(forms.Form):
authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
更新
如果需要一个动态模型选择字段,您可以将您的商品ID移交给表单的构造函数,并相应地调整查询集:
If you need a dynamic model choice field, you can hand over your item id in the constructor of the form and adjust the queryset accordingly:
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)
聚苯乙烯我尚未测试此代码,也不确定您的确切设置,但希望能理解主要思想。
P.S. I haven't tested this code and I'm not sure about your exact setup, but I hope the main idea comes across.
资源:
- http://www.mail-archive.com/django-users@googlegroups.com/msg48058.html
- http://docs.djangoproject.com/en/dev/ref/forms/fields/#django。 form.ModelChoiceField
- http://www.mail-archive.com/django-users@googlegroups.com/msg48058.html
- http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField
这篇关于在视图中使用数据库中的数据填充Django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!