I'm using this form to get a dropdown menu in my html form :
forms.py
class forms_bdc(forms.ModelForm):
[...]
bdc_description_1 = forms.ModelChoiceField(required=False,queryset=models_products.objects.values_list('product_denomination', flat=True), widget=forms.Select(attrs={'id': 'editable-select-2','onchange': 'populate_selected_product(this.id)'}),empty_label=None )
models.py
class models_bdc(models.Model):
[...]
bdc_description_1 = models.CharField(max_length=50)
But when I save / submit the form, the data are not saving into the database.
If I remove the select widget to a regular forms.charfield, the datas are saving correctly.
So I assume the mistake is the forms.py but I can't see where.
Thanks
Short answer:
# forms.py
class forms_bdc(forms.ModelForm):
# ...
bdc_description_1 = forms.ChoiceField(
required=True,
choices=(
('option value', 'option label'),
),
widget=forms.Select(attrs={'class': 'your-class'}),
# ...
)
Long answer:
advise: for django forms, use PascalCase and end the name with "Form" (convention).
#forms.py
from .models import OPTIONS
class BdcForm(forms.ModelForm):
# ...
bdc_description_1 = forms.ChoiceField(
required=True,
choices=OPTIONS,
widget=forms.Select(attrs={'class': 'your-class'}),
# ...
)
# models.py
OPTIONS = (
('option value', 'option label'),
# ...
)
you can set expected values in models and just import and reuse anywhere you want.