首页 > 解决方案 > 如何保存包含容器 div 的表单,其中包含已在 django 中动态添加的子 div

问题描述

我正在开发一个工作门户系统。我为用户提供了通过添加和删除工作经验来编辑他们的个人资料的机会。问题是我不知道如何将该数据发送到视图,以便它可以检索所有字段并将它们相应地存储在数据库中。通过检索,我的意思是对于每个工作经验,检索它们对应的子字段

这是我的模板文件:

<!--JOB EXPERIENCE-->

        <div class="job_experience">
            <h5>Experience</h5>
            <hr>

            <!--FORM-->
            <form action="#" id="save_job_experience_form" method="POST">
                {% csrf_token %}
            <div class="job_container">
                {% for job in job_experience %}
                <div class="exp">
        
                 <label>Organisation</label>
                 <input type="text" class="form-control" name="organisation 
                 placeholder="Organisation" value="{% if job.organisation %} 
                 {{job.organisation}}{% endif %}" required>
     
        
                 <label>Job Title</label>
                 <input type="text" name="job_title" class="form-control" value="{% if job.job_title 
                  %}{{ job.job_title }}{% endif %}" placeholder="Job Title e.g Backend Developer" 
                 required>
                      
                
                <button style="margin-left:15px;" type="button" class="btn btn-danger 
                remove_job_exp"><strong>Delete Job Experience</strong></button>
            </div>
            <hr>
           {% endfor %}
               
        </div>
                <!--BUTTONS-->
                <input type="submit"value="Save">
                <input type="button"  id="add_job_experience"value="Add one">
            
            </form>
        </div>

  <script>
        $(document).on('click', '#add_job_experience',function(e){
            e.preventDefault();
            $(".job_container").append(`<div class="exp">
                <!--IT GOES ON AS ABOVE -->

        $(document).on('click', 'button.remove_job_exp', function(e){
            e.preventDefault();
            $(this).closest('div.exp').remove();
        });

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


您可以发布多个具有相同名称的输入,如下所示:

<input type="text" name="job[]" value="job1"/>
<input type="text" name="org[]" value="org1"/>
<input type="text" name="job[]" value="job2"/>
<input type="text" name="org[]" value="org2"/>

然后在 django 中,您可以像这样解析POST数据:

@require_POST #require POST method or check if request method is POST
def add_jobs(request):
    jobs = request.POST.getlist('job[]')
    orgs = request.POST.getlist('org[]')
    ... 

或使用 Django 表单集:https ://docs.djangoproject.com/en/3.2/topics/forms/formsets/


推荐阅读