Dynamic ChoiceField
I am on Django 5.1.1. I have a IngredientFormSet
for IngredientForm(forms.Form)
. The form has a ChoiceField as shown in snippet below. The number of ingredients are a few thousand in IngredientModel
. JS library select2
has been used in the UI so that user can type in this field, and select2
filters the names using an Ajax call.
Now, when I submit the form, I get error that the id of the ingredient name is not part of the choices (as choices=[]
), which is expected, but obviously it doesn't work for my case.
I want to update the IngredientForm.__init__(self, *args, **kwargs)
such that whatever ingredient_id I get in the kwargs, I will query if an ingredient with that id exists in the table, and if so, then add that single value to the choices.
class IngredientForm(forms.Form):
ingredient = forms.ChoiceField(
label='Ingredient name',
required=True,
choices=[],
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
form_ingredient_id = ? # how to get hold of value of option here?
if IngredientModel.objects.filter(id=form_ingredient_id).exists():
self.fields['ingredient'].choices = [(form_ingredient_id, form_ingredient_id)]
So how do I get hold of the ingredient_id which select2 has put in the form choicefield? Note that when initializing the formset, I use custom prefix.