使用视图中的数据库数据填充 Django 表单 [英] Populate a django form with data from database in view

查看:22
本文介绍了使用视图中的数据库数据填充 Django 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 forms.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:

基本上,您可以在 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())

<小时>

更新

如果你需要一个动态模型选择字段,你可以在form的构造函数中交出你的item id并相应地调整queryset:

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.

资源:

这篇关于使用视图中的数据库数据填充 Django 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆