django ModelMultipleChoiceField set initial values

て烟熏妆下的殇ゞ 提交于 2019-12-10 01:23:29

问题


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"


回答1:


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



回答2:


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

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

The tricky part is that you must have the right queryset. Just like the seed values, it must be of Category.objects.filter(...) - anything else won't work.




回答3:


Either set initial when you create form instance or set field initial in 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 selected you can set empty_label property. https://docs.djangoproject.com/en/1.10/ref/forms/fields/#django.forms.ModelChoiceField.empty_label



来源:https://stackoverflow.com/questions/26966527/django-modelmultiplechoicefield-set-initial-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!