djangoselectdjango-queryset

Django query for a select item return '---------'


I'm trying to populate a select item with a django queryset. It's working fine but at the begining of the list of the dropdown menu on the select item I always have a '---------' as first option.

forms.py

class forms_bdc(forms.ModelForm):
[...]
    bdc_description_1 = forms.ModelChoiceField(queryset=models_products.objects.values_list('product_denomination', flat=True),required=False, widget=forms.Select(attrs={'id': 'editable-select-2'}))

The "product_denomination" on the database only contains 2 lines but I always have this '---------' on first option.

What am I missing ?


Solution

  • The '---------' that appears as the first option in your ModelChoiceField is the default empty option that Django adds for optional fields. To remove this option, you can set the empty_label attribute to None.

    Here’s how you can modify your forms.py:

    class forms_bdc(forms.ModelForm):
        [...]
        bdc_description_1 = forms.ModelChoiceField(
            queryset=models_products.objects.values_list('product_denomination', flat=True),
            required=False,
            widget=forms.Select(attrs={'id': 'editable-select-2'}),
            empty_label=None  # This removes the '---------' option
        )