django ChoiceField に初期データを入力する方法がわかりません。ビューに渡すパラメーターに応じて変更されるため、ビューで実行することをお勧めします。
ビュー.py
def index(request):
init_ingredients = [{'food':'Candy','amt':12,'units':'cup'},{'food':'Bacon','amt':9,'units':'cup'}]
IngredientsFormSet = formset_factory(IngredientLineForm, can_delete=True)
if request.method == 'POST':
formset = IngredientsFormSet(request.POST, request.FILES)
...
else:
formset = IngredientsFormSet(initial=init_ingredients)
「food」フィールドと「amt」フィールドには値が入力されますが、html Select 入力である「units」フィールドには初期値が入力されません。選択肢も定義する必要がありますか? 初期値はそれらの1つですか?
フォーム.py
class IngredientLineForm(forms.Form):
food = forms.CharField(widget=forms.TextInput(attrs={'class':'foods form-control'})) #class = food
units = forms.ChoiceField(widget=forms.Select(attrs={'class':'units form-control'}))
amt = forms.CharField(widget=forms.NumberInput(attrs={'class':'amt form-control'}))