首页 > 解决方案 > 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>

我能够将它们呈现在相同的行上,但它们都带有标签。

  1. 有没有办法呈现只显示标签的表单thismonth,而lastmonth只显示值而不手动指定字段 id 和 name?
  2. 另外,由于我不想更改lastmonth的值,有没有办法只从request.POST获取thismonth值以便保存/更新它?

标签: djangodjango-templatesmodelform

解决方案


  1. 是的,您可以基本上像这样单独呈现每个表单字段:
[...]

<tr><td>{{ thismonth.as_p }}</td>
<td>{{ lastmonth.form_field }}</td></tr>

[...]

这样您就可以控制应该呈现哪些表单的标签,哪些不应该呈现。

  1. 是的,您可以像这样获取单个值:
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 [...]

推荐阅读