0

我正在构建一个表格,允许员工进入城市、行程状态并自动计算他们的里程报销。现在我在 forms.py 中有以下代码:

leg1a = forms.CharField(max_length=20, required=False)
leg1b = forms.CharField(max_length=20, required=False)
leg2a = forms.CharField(max_length=20, required=False)
leg2b = forms.CharField(max_length=20, required=False)
leg3a = forms.CharField(max_length=20, required=False)
leg3b = forms.CharField(max_length=20, required=False)
leg4a = forms.CharField(max_length=20, required=False)
leg4b = forms.CharField(max_length=20, required=False)
leg5a = forms.CharField(max_length=20, required=False)
leg5b = forms.CharField(max_length=20, required=False)
leg6a = forms.CharField(max_length=20, required=False)
leg6b = forms.CharField(max_length=20, required=False)

然后我使用一个单独的脚本来计算每条腿的里程,并将总和乘以我们的里程率。它有效,但在形式上很难看;该表单有六对都是可选的字段。我希望有 1 对开始,并且用户可以单击一个选项来添加另一条腿。

我需要以元组形式保存数据,如下所示:('city, ST','city2, ST')用于距离计算功能。

这是我目前在表单视图中使用的代码,用于清理数据并将数据发送到里程处理程序:

里程距离计算

        leg_list = [(leg1a, leg1b), (leg2a, leg2b), (leg3a, leg3b), (leg4a, leg4b), (leg5a, leg5b), (leg6a, leg6b)]
        
        cleaned_leg_list = []
        #get rid of empty variables
        for leg in leg_list:
            if leg == ('',''):
                pass
            else:
                cleaned_leg_list.append(leg)
        leg_distance = []
        #sends each leg of mileage claim to distance handler
        for leg in cleaned_leg_list:
            pre_leg = main(leg)
            leg_distance.append(pre_leg)
        #sums legs of mileage claim 
        sum_distance = sum(leg_distance)
4

1 回答 1

3

使用一个表单和一个表单集。表单集处理处理一个表单的多个实例。

https://docs.djangoproject.com/en/dev/topics/forms/formsets/

或者,您可以查看通过 javascript 克隆表单集,以便在不重新加载视图的情况下动态添加任意数量的区域。

这也是清理代码的好机会 - 在表单定义上放置一个计算腿距离并调用外部脚本的方法。您的视图可以在几行代码中进行汇总!

您甚至可以自己构建 formset 类并在其中添加求和函数,因此您的视图非常简单:if formset.is_valid(): print formset.sum_leg_distances()

class MyForm(forms.Form):
    start_city = forms.CharField()
    start_state = forms.CharField()
    end_city = forms.CharField()
    end_state = forms.CharField()

MyFormSet = formset_factory(form=MyForm, extra=6)

def my_view(request):
   formset = MyFormSet(request.POST or None)
   if request.POST:
       if formset.is_valid():
           for form in formset.forms:
               form.cleaned_data['start_city'] # here's your leg data.
               # form.calculate_leg_distance()
           # sum([form.calculat_leg_distance() for form in formset])


   return render(request, 'my_template', {'formset': formset})

<form method="post">
   {{ formset.as_p }}
   {{ formset.management_form }}
<input type="submit" />
</form>
于 2012-08-20T02:33:54.313 回答