使用数据库(而不是模型)中的选项填充Django表单字段

时间:2019-06-06 15:43:42

标签: django django-forms

我想用数据库中的数据填充表单下拉列表。 这些数据不是直接来自模型,而是来自原始查询。

当数据库可用且已经生成迁移时,此方法有效。否则,生成迁移(python manage.py makemigrations myapp)会失败,因为Django评估无法找到适当表的_all_departments()

def _all_departments() -> List[Tuple[str, str]]:
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute("select distinct department from crm_mytable order by department")
        return [(row[0], row[0]) for row in cursor.fetchall()]


class MyForm(forms.Form):
    department = forms.CharField(
        widget=forms.SelectMultiple(choices=_all_departments()))

我天真地尝试手动更新__init__上的选择,但没有成功(选择始终为空):

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['department'].widget.choices = _all_departments()

    department = forms.CharField(
        widget=forms.SelectMultiple(choices=[]))

正确选择按需选择的方式是什么?

1 个答案:

答案 0 :(得分:2)

您不应不要choices传递给 widget ,而应传递给 field 。您可能还想使用MultipleChoiceField [Django-doc],它使用SelectMultiple [Django-doc]作为默认小部件:

class MyForm(forms.Form):

    department = forms.MultipleChoiceField(choices=[])

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['department'].choices = _all_departments()