如何在django中为ModelMultipleChoiceField创建自定义树窗口小部件?

时间:2017-05-15 09:27:47

标签: python django python-3.x django-widget django-1.10

在我的表单中,我有function字段,ModelMultipleChoiceField我希望添加用户功能选择的字段。由于queryset函数字段占用Group的所有对象。有人可以帮我创建自定义小部件,如下图所示吗?下面还可以看到我的小部件的html(tree_widget.html)。

enter image description here

tree_widget.html:

{% for group in groups %}
    <p>{{ group }}</p>
    {% for task in group.task_set.all %}
        <p>{{ task }}</p>
        {% for function in task.function_set.all %}
            <p>
               <input type="checkbox" name="option" value="{{ function }}">{{ function }}
            </p>
        {% endfor %}
    {% endfor %}
{% endfor %}

forms.py:

class RequirementForm(forms.ModelForm):
    function = forms.ModelMultipleChoiceField(required=True, widget=CustomTreeWidget, queryset=Group.objects.none())

    class Meta:
        model = Requirement
        fields = ('function',)

    def __init__(self, all_groups, all_user_characteristics, *args, **kwargs):
        super(RequirementForm, self).__init__(*args, **kwargs)
        self.fields['function'].queryset = all_groups  # I take all Group objects from view

widgets.py:

class CustomTreeWidget(CheckboxSelectMultiple):
    template_name = 'tree_widget.html'
    ???

0 个答案:

没有答案