Django:将字典/列表数据发送到表单

时间:2017-01-20 13:55:59

标签: django forms dictionary listbox dropdown

目标:将数据字典发送到表单,以便在下拉框中使用。

Views.py

form = FormsdbForm(initial={'user': default_state})
# (to set the default value of the 'user' field)

Forms.py

class FormsdbForm(forms.ModelForm):
    ROOMLIST = (('roomID_abcdefghi','Room ABC'),
                ('roomID_jklmnopqr','Room JKL'))
    roomid = forms.ChoiceField(required=False, choices=ROOMLIST)

    class Meta:
        model = Formsdb
        fields = ('user', 'uniqueid', 'roomid')

以上设置显示一个表单,其中字段'roomid'是显示条目的下拉框:

  • ABC室
  • Room JKL

保存后,数据库将填充匹配的“RoomID_xxxxxxxxx” 到目前为止完美!

在我的Views.py中,我有一个字典(我可以轻松转换为列表列表),其中包含现在在Forms.py(ROOMLIST)中静态配置的数据。

问题: 如何将此词典(或列表)传递给表单,以便显示带有选项的下拉框?

这将替换当前的“ROOMLIST”变量,它可以轻松包含400-600个条目。

1 个答案:

答案 0 :(得分:0)

观点:

from django.views.generic import FormView

class FormsdbView(FormView):
    # ...

    def get_form_kwargs(self):
        kwargs = super(FormsdbView, self).get_form_kwargs()
        ROOMLIST = (('roomID_abcdefghi','Room ABC'),
                   ('roomID_jklmnopqr','Room JKL'))
        kwargs['roomlist'] = ROOMLIST
        return kwargs

如果您未使用FormView,则可能还会form = FormsdbForm(initial={'user': default_state}, roomlist=ROOMLIST)

表格:

from django import forms

class FormsdbForm(forms.ModelForm):

    roomid = forms.ChoiceField(required=False)
    # ...

    def __init__(self, *args, **kwargs):
        self.roomlist = kwargs.pop('roomlist', None)
        super(FormsdbForm, self).__init__(*args, **kwargs) 
        self.fields['roomid'].choices = self.roomlist