此类帖子与this one类似,但似乎都没有回答我的问题。我正在尝试使用ManyToMany
向Django中的ModelForms
字段添加内容,但我一直收到错误消息。我的代码看起来像:
models.py:
class LineSection(models.Model):
...
class Line(models.Model):
line_id = models.IntegerField()
...
sections = models.ManyToManyField(LineSection)
class LineForm(ModelForm):
class Meta:
model = Line
fields = [...,'sections']
views.py:
partialLine = Line(user=1001)
line = LineForm(request.POST.copy(), instance=partialLine)
...
newSect = Section(sect_id=sectId,
point_list=sect['point_list'],
...)
try:
newSect.save()
line.sections.add(newSect)
except Exception as e: ...
我收到错误:
'LineForm'对象没有属性'sections'。
有什么想法吗?
答案 0 :(得分:0)
正如错误所示:line
是LineForm
的实例,而不是Line
。您需要在某个时刻保存表单对象以获取实际更新的模型实例:
line_obj = line.save()
虽然您应该重命名令人困惑的line
对象。