加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

使用数据库中的数据填充django表单

发布时间:2020-12-12 16:29:55 所属栏目:MsSql教程 来源:网络整理
导读:我的form.py中有一个表单,如下所示: from django import formsclass ItemList(forms.Form): item_list = forms.ChoiceField() 我需要使用数据库中的某些数据填充item_list.当在HTML item_list中生成时应该是这样的: select title="ItemList" option value="
我的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>

select语句中的options值几乎会每次更改,因为查询中的变量通常会更改生成新结果.

我需要放在view.py以及我的模板文件中,用数据库中的值填充ItemList?

解决方法

看看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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读