我正在尝试使用基于类的视图来显示有关工具的信息,然后向该视图添加标签,主要是为了自学如何使用 inline_formsets。我遇到的问题是如何将子对象的表单注入模板。
问题是出现了孩子的表单集,但没有从模板显示父表单。
结果是父表单不显示 -
最终,这是一个“我在 Django 中做错了什么?” 问题。
该模型非常简单 - 工具有几个字段定义我的父对象,标签是与之相关的子对象:
模型.py
from django.db import models
class Tool(models.Model):
content_id = models.CharField(
primary_key=True,
help_text="Confluence ID of the tool document",
max_length=12
)
tool_name = models.CharField(
max_length=64,
help_text="Short name by which the tool is called",
)
purpose = models.TextField(
help_text="A one sentence summary of the tools reason for use."
)
body = models.TextField(
help_text="The full content of the tool page"
)
last_updated_by = models.CharField(
max_length=64
)
last_updated_at = models.DateTimeField()
def __unicode__(self):
return u"%s content_id( %s )" % (self.tool_name, self.content_id)
class ToolTag(models.Model):
description = models.CharField(
max_length=32,
help_text="A tag describing the category of field. Multiple tags may describe a given tool.",
)
tool = models.ForeignKey(Tool)
def __unicode__(self):
return u"%s describes %s" % (self.description, self.tool)
我正在使用标准的基于类的表单:
表格.py
from django.http import HttpResponseRedirect
from django.views.generic import CreateView
from django.views.generic import DetailView, UpdateView, ListView
from django.shortcuts import render
from .forms import ToolForm, TagsFormSet
from .models import Tool
TagsFormSet = inlineformset_factory(Tool, ToolTag, can_delete='True')
class ToolUpdateView(UpdateView):
template_name = 'tools/tool_update.html'
model = Tool
form_class = ToolForm
success_url = 'inventory/'
视图.py
def call_update_view(request, pk):
form = ToolUpdateView.as_view()(request,pk=pk)
tag_form = TagsFormSet()
return render( request, "tools/tool_update.html",
{
'form': form,
'tag_form': tag_form,
'action': "Create"
}
)
我的模板如下:
工具更新.html
{% block content %}
<form action="/update/" method="post">
{% csrf_token %}
<DIV>
Tool Form:
{{ form.as_p }}
</DIV>
<DIV>
Tag Form:
{{ tag_form.as_p }}
</DIV>
<input type="submit" value="Submit" />
</form>
{% endblock %}