我正在构建一个表格,允许员工进入城市、行程状态并自动计算他们的里程报销。现在我在 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)