django - Django 在模板中渲染多个 ModelForm 并保存
问题描述
我有一个 django Entry模型,它接受与身高、体重等实体相关的几个值。这个值必须每个月输入。对于每个月,必须在模板上显示一个新表格以及上个月的数据。我的观点有点像这样:
ntt=Entry.objects.get(pk=6)
lastmonth=EntryForm(instance=ntt)
thismonth=EntryForm()
return render(request, 'show.htm', {'thismonth':thismonth,'lastmonth':lastmonth})
我不知道如何并排显示这两个值,每个属性一行如下:
<tr><td><input type=text>thismonth.weight</input></td><td>lastmonth.weight</td></tr>
<tr><td><input type=text>thismonth.height</input></td><td>lastmonth.height</td></tr>
使用常见的方式来呈现像{{thismonth.as_p}}{{lastmonth.as_p}}这样的表单
<table>
<tr>
<td>{{thismonth.as_p}}</td>
<td>{{lastmonth.as_p}}</td>
</tr>
</table>
我能够将它们呈现在相同的行上,但它们都带有标签。
- 有没有办法呈现只显示标签的表单thismonth,而lastmonth只显示值而不手动指定字段 id 和 name?
- 另外,由于我不想更改lastmonth的值,有没有办法只从request.POST获取thismonth值以便保存/更新它?
解决方案
- 是的,您可以基本上像这样单独呈现每个表单字段:
[...]
<tr><td>{{ thismonth.as_p }}</td>
<td>{{ lastmonth.form_field }}</td></tr>
[...]
这样您就可以控制应该呈现哪些表单的标签,哪些不应该呈现。
- 是的,您可以像这样获取单个值:
def your_view(request):
if request.method == 'POST': # If the form has been submitted...
form = EntryForm(request.POST) # A form bound to the POST data
if form.is_valid():
print form.cleaned_data['my_form_field_name']
return [...]
推荐阅读
- java - mvn gwt:在“后台”运行什么?
- c++ - 是否可以使用 typedef 来指定模板类的几种类型?
- kubernetes - 当 Pod 在 OpenShift 中自动缩放时如何接收警报
- r - 如何获取导致“未定义列选择”错误的列名?
- javascript - 如何确定 Material UI 中的 popupState 是否已打开
- pytest - 使用 pytest,我如何断言断言确实发生了?
- ios - 在另一个类/扩展中使用完成处理程序
- python - Python:跨平台路径对象生成器
- powershell - powershell - 读取文件夹中的所有 .sql 文件并将它们全部保存到单个 .sql 文件中,而无需更改换行符或换行符
- python - - 不支持的操作数类型:“int”和“str”