djangodjango-formsmultiplechoicefield

django ModelMultipleChoiceField set initial values


I have the following code:

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"


Solution

  • 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)
            ]
        }
    )