本文介绍了django ModelMultipleChoiceField设置初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
category = forms.ModelMultipleChoiceField(
label="Category",
queryset=Category.objects.order_by('name'),
widget=forms.Select(
attrs={
'placeholder': 'Product Category', 'class': 'form-control'}),
required=True
)
在选择类别之类的选择框中设置初始值,以便选择框应具有初始值为选择类别的类别列表
how do I set an initial value in the select box like "Choose a category" so that the select box should have a list of categories with the initial value being "Choose a category"
推荐答案
如果您将 QuerySet
对象作为初始值传递,并且 widget = forms.CheckboxSelectMultiple
,则未选中复选框。我必须将 QuerySet
对象转换为列表,然后选中复选框:
If you pass a QuerySet
object as an initial value and if widget=forms.CheckboxSelectMultiple
, then the check boxes are not checked. I had to convert the QuerySet
object to a list, and then the check boxes were checked:
YourForm(initial={'multi_field':
[cat for cat in Category.objects.all().values_list('id', flat=True)]
})
这篇关于django ModelMultipleChoiceField设置初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!