django - 如何保存包含容器 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();
});
解决方案
您可以发布多个具有相同名称的输入,如下所示:
<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/
推荐阅读
- micronaut - Micronaut - 解析属性文件中的占位符
- angular - 如何自定义 ngx-charts(折线图)以始终显示工具提示?
- nlp - WordPiece 标记化如何有助于有效处理 NLP 中的稀有词问题?
- cordova - cordova platform add ios --save exited with exit code 1
- node.js - "TypeError [ERR_INVALID_ARG_TYPE]" - MP3 & VC
- amazon-web-services - 如何将参数从 aws 状态机/步进函数传递到 aws lambda
- python - Tkinter 按钮小部件找不到图像,错误图像不存在
- javascript - 如何使用jquery通过单击按钮启用和禁用链接
- javascript - 使用 load_paths 时找不到 Jekyll node_modules
- sql - 试图将 '=countifs' 函数从 excel 复制到 SQL