我不知道如何用初始数据填充 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' 字段填充,但 'units' 字段 - 这是一个 html Select 输入不填充初始值。我也需要定义选择吗?并且初始值是其中之一吗?
表格.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'}))