Django ModelMultipleChoiceField sets 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 to set the initial value in the selection field, for example, "Select a category", so that the selection field has a list of categories with the initial value "Select a category"

+8
django django-forms
source share
3 answers

You can pass it the "initial" setting from your view. For example:

 form = FormUsingCategory(initial={'category':querysetofinitialvalues}) 

The tricky part is that you have to have the right set of queries. Just like seed values, it must be from Category.objects.filter (...) - nothing else will work.

+10
source share

Either set the initial value when you instantiate the form or specify the initial field in the form init

 def __init__(self, *args, **kwargs): super(YourForm, self).__init__(*args, **kwargs) self.fields["category"].initial = ( Category.objects.all().values_list( 'id', flat=True ) ) 

If you just want to change the text when no field is selected, you can set the empty_label property. https://docs.djangoproject.com/en/1.10/ref/forms/fields/#django.forms.ModelChoiceField.empty_label

+8
source share

If you pass the QuerySet object as the initial value, and if widget=forms.CheckboxSelectMultiple , then the checkboxes will not be widget=forms.CheckboxSelectMultiple . I had to convert the QuerySet object to a list, and then the checkboxes were checked:

 YourForm(initial={'multi_field': [cat for cat in Category.objects.all().values_list('id', flat=True)] }) 
+1
source share

All Articles