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