我需要选择复选框的多个初始值,这些初始值是使用小部件调整呈现的。
当我只有一个初始值时,我的代码工作得很好。但是,如果初始值超过1个,则在复选框中只会选中第一个。
forms.py
class GroupForm(forms.ModelForm):
class Meta:
model = Group
fields = ('name', 'category', 'pods')
def __init__(self, group_id, category_id, *args, **kwargs):
super(GroupForm, self).__init__(*args, **kwargs)
selected_group = Group.objects.get(id=group_id)
self.fields['name'].initial = selected_group.name
self.fields['category'].initial = selected_group.category.id
self.fields['pods'].queryset = Pod.objects.filter(category=selected_group.category.id)
associated_pods = selected_group.pod.all()
self.fields['pods'].initial = [pod.id for pod in associated_pods]
views.py
def GroupUpdate(request,id):
group = get_object_or_404(Group, pk=id)
context = {}
group_id = group.id
category_id = request.GET.get('category')
context['form'] = GroupForm(group_id, category_id)
return render(request, 'catalog/group_detail.html', context)
html文件
...
<div class="form-group">
<label class="col-md-3 control-label">Group's Members</label>
<div class="col-md-6">
<div class="input-group btn-group">
<span class="input-group-addon">
<i class="fa fa-th-list"></i>
</span>
{% render_field form.pods|attr:"multiple:multiple"|attr:"data-plugin-multiselect" title="group_member" class="form-control" %}
</div>
</div>
</div>
...
我需要复选框的预选初始值才能动态呈现。 当前self.fields ['pods']。initial = [associated_pods中pod的pod.id]仅勾选一个复选框,尽管关联的pod超过一个。
答案 0 :(得分:0)
我认为我的调查取得了一些进展。这个jQuery data-plugin-multiselect以某种方式仅接受单个初始值。也许任何人都知道如何调整此jquery以使其能够接受多个初始值。
答案 1 :(得分:0)
这可以通过将小部件添加到表单中来解决
pods = forms.ModelChoiceField(
queryset=Pod.objects.all(),
required=False,
empty_label=None,
widget=forms.SelectMultiple,
)