将自定义表单字段保存到数据库的有效方法

时间:2013-08-28 19:03:35

标签: django django-forms

我无法将许多字段保存到数据库中。我有很多'outcomevalue_#'字段,根据我的结果数量生成。用户选择结果子集(相关结果)并输入相关值。我想用结果保存相关的值。到目前为止,我只能硬连接那些无法解决问题的字段名称。

views.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)

forms.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

因为它抓取列表中的值而不是索引位置

2 个答案:

答案 0 :(得分:0)

如果我理解正确的话,那你就试图使用一对一的关系,那里应该有一对多的关系。如果您要为一个StateOption设置多个Outcomes,我是否可以建议您使用多对多桥接表来链接哪个StateOption具有哪些Outcome(s)。然后在该桥接表中,您还可以将相关值存储为适当的StateOption / Outcome对的附加列。

答案 1 :(得分:0)

使用以下方法解决它:

outcomelist = request.POST.getlist('relevantoutcome')
       for i,outcome_id in enumerate(outcomelist):
           cd = form.cleaned_data
           outcomevalue = cd['outcomevalue_%s' % outcomelist[i]]   

           stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue)