我无法将许多字段保存到数据库中。我有许多“结果价值_#”字段,这些字段是根据我拥有的结果数量生成的。用户选择结果子集(相关结果)并输入相关值。我想将相关值与结果一起保存。到目前为止,我只能硬连线不能解决问题的字段名称。
视图.py
stateoption = get_object_or_404(StateOption, pk=stateoption_id)
if request.method == "POST":
form = UpdateStateOptionWithOutcomesForm(request.POST, instance=stateoption)
if form.is_valid():
cd = form.cleaned_data
outcomevalue = cd['outcomevalue_1'] #hardwired. This needs to be generalized.
for outcome_id in request.POST.getlist('relevantoutcome'):
stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue)
表格.py
class UpdateStateOptionWithOutcomesForm(forms.ModelForm):
class Meta:
model = StateOption
def __init__(self, *args, **kwargs):
super(UpdateStateOptionWithOutcomesForm, self).__init__(*args, **kwargs)
self.fields['relevantoutcome']=forms.ModelMultipleChoiceField(queryset=Outcome.objects.all(),required=True, widget=forms.CheckboxSelectMultiple)
outcome_qs=Outcome.objects.all()
for outcome in outcome_qs:
self.fields['outcomevalue_%s' % outcome.pk] = forms.CharField(required=False)
更新
这是我的精简models.py
class StateOptionOutcome(models.Model):
stateoption = models.ForeignKey(StateOption)
relevantoutcome = models.ForeignKey(Outcome)
outcomevalue = models.CharField(max_length=20)
在玩了一些之后,我有类似的东西:
outcomelist = request.POST.getlist('relevantoutcome')
for outcome_id in outcomelist:
cd = form.cleaned_data
outcomevalue = cd['outcomevalue_%s' % outcomelist[int(outcome_id)]]
stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue)
但得到错误:
list index out of range
因为它正在获取列表中的值而不是索引位置