在Django post-request中选择相同形式的两个实例

时间:2016-06-24 17:14:28

标签: django

我有以下问题,最好通过示例描述。

首先,我将两个相同形式的实例发送到Django模板。

查看1:

def view_1
leg_address_form = AddressForm()
fct_address_form = AddressForm()
return render_to_response('my_template.html',
                          {'leg_address_form':leg_address_form,
                           'fct_address_form':fct_address_form},...

在此之后,当在my_template中的某处按下提交按钮时,我必须处理请求,我无法从两个表单实例访问数据。

观看2:

def employee_create(request.POST):
    leg_address_form = AddressForm(request.POST) #how could I know which one is it?
    fct_address_form = AddressForm(request.POST) #how could I know which one is it?

1 个答案:

答案 0 :(得分:2)

您可以使用prefix为每个Form提供自己的命名空间。

def main_view(request):
    if request.method == 'POST':
        leg_address_form = AddressForm(request.POST, prefix='leg')
        fct_address_form = AddressForm(request.POST, prefix='fct')
        # do something with data
    else:
        leg_address_form = AddressForm(prefix="leg")
        fct_address_form = AddressForm(prefix="fct")
    return render_to_response('my_template.html',
                      {'leg_address_form':leg_address_form,
                       'fct_address_form':fct_address_form},...