Django:独立保存表单

时间:2014-10-24 14:30:51

标签: html django django-forms django-views

我在同一个模板中的两个不同标签中有两个表单。表格的模型通过外键连接。

当我尝试单独保存每个表单时,每个表单都有一个提交按钮,但不幸的是,这两个表单正在尝试再次保存数据,即使我只按一个提交按钮。

Views.py

def input(request):
    my_demographics = DemographicForm(request.POST or None)
    my_diagnosis = DiagnosisForm(request.POST or None)

    context = RequestContext(request)
    if request.method == 'POST':
        submitted = request.POST.get('form_id', '')

        if submitted == 'demographics':
            # Get the Form1 instance
            my_demographics = DemographicForm(request.POST)
            if my_demographics.is_valid():
                my_demographics_object= my_demographics.save()
                my_diagnosis=DiagnosisForm({'patient': my_demographics_object.patient_id})


        elif submitted == 'diagnosis':
            # Get the Form2 instance
            my_diagnosis = DiagnosisForm(request.POST)
            if my_diagnosis.is_valid():
                my_diagnosis.save()

        else:
            raise ValueError('No form specified !')


return render_to_response('input.html', {'frm':my_demographics, 'frm_d': my_diagnosis}, context)

input.html

<div class="tab-content">

    <!-- Tab panes -->
    <form class="tab-pane fade in active" id="demographics" method="post" >
        <input type="hidden" name="form_id" value="demographics">
        {%crispy frm%}
    </form>
    <form class="tab-pane fade" id="diagnosis" method="post">
         <input type="hidden" name="form_id" value="diagnosis">
        {%crispy frm_d%}
    </form>
</div>

2 个答案:

答案 0 :(得分:4)

首先在每个表单中添加一个隐藏的输入,它将指定发布的表单:

<div class="tab-content">

    <!-- Tab panes -->
    <form class="tab-pane fade in active" id="demographics" method="post" >
        <input type="hidden" name="form_id" value="demographics"> 
        {%crispy frm%}
    </form>
    <form class="tab-pane fade" id="diagnosis" method="post">
        <input type="hidden" name="form_id" value="diagnosis"> 
        {%crispy frm_d%}
    </form>
</div>

然后在您的视图中,检查发布的表单并仅保存此表单。

编辑:

def input(request):
    context = RequestContext(request)
    if request.method == 'POST':
        submitted = request.POST.get('form_id', '')

        if submitted == 'demographics':
            # Get the Form1 instance
            my_demographics = DemographicForm(request.POST)
            if my_demographics.is_valid():
                my_demographics_object= my_demographics.save()
                my_diagnosis=DiagnosisForm({'patient': my_demographics_object.patient_id})
             else:
                my_diagnosis=DiagnosisForm()

        elif submitted == 'diagnosis':
            # Get the Form2 instance
            my_diagnosis = DiagnosisForm(request.POST)
            if my_diagnosis.is_valid():
                my_diagnosis.save()
                # here you should redirect

            my_demographics = DemographicForm()

        else:
            raise ValueError('No form specified !')

    else:
        my_demographics = DemographicForm()
        my_diagnosis = DiagnosisForm()

    return render_to_response(
        'input.html', 
         {'frm':my_demographics, 'frm_d': my_diagnosis}, 
         context
         )

答案 1 :(得分:0)

视图将具有仅在提交的表单内的输入名称,这就是您现在的方式,因此您可以添加隐藏字段并检查其值,如果是form1或form2,那么您知道已经提交了一个!

if request.POST:
    # Get the form submitted
    submitted = request.POST.get('form_name', '')

    if submitted == 'form1'
        # Get the Form1 instance
        form = Form1Model(request.POST)

    elif submitted == 'form2'
        # Get the Form2 instance
        form = Form2Model(request.POST)
    else:
         raise ValueError('No form specified !')

    # Validate the form
    if form.is_valid():
        # If the form is valid save it
        if form.save():
            # correct data entry
            messages.info(
                request,
                _(u"Fichier copié sur le DHS, mise à jour en cours ...")
            )
        else:
            # Can't save the form
            messages.warning(
                request,
                _(u"Un problème est survenu pendant l'enregistrement "
                  u"des données, merci de réessayer plus tard.")
            )
    else:
        # Form is not valid, show feedback to the user
        messages.error(
            request,
            _(u"Merci de corriger les erreurs suivantes.")
        )
else:
    # Empty forms this is the first call
    form1 = Form1Model()
    form2 = Form2Model()

    # Disclaimer
    messages.warning(
        request,
        _(u"L'interface web sera inaccessible durant la mise à jour.")
    )