让用户向Django表单添加字段

时间:2012-08-20 01:19:14

标签: python django django-forms

我正在建立一个表格,允许员工进入城市,行程状态并自动计算他们的里程报销。现在我在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)
然后,我使用一个单独的脚本计算每条腿的里程数,并将总数乘以我们的里程数。它有效,但在形式上很难看;表单有六对字段,都是可选的。我希望有一对开始,用户可以点击添加另一条腿的选项。

我需要将数据保存为元组形式,如下所示:('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)

1 个答案:

答案 0 :(得分:3)

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

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>