简体   繁体   English

Django ManyToMany字段返回错误“对象没有属性”

[英]Django ManyToMany field returns error 'object has no attribute'

There are similar posts to this like this one , but none of them seem to answer my question. 类似的还有职位,这个喜欢这一个 ,但他们都不回答我的问题。 I am trying to add something to a ManyToMany Field in Django using ModelForms , but I keep getting an error. 我正在尝试使用ModelForms将某些东西添加到Django中的ManyToMany字段中,但是我一直遇到错误。 My code looks something like: 我的代码如下所示:

models.py: 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: 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: ...

I get the error: 我收到错误:

'LineForm' object has no attribute 'sections'. “ LineForm”对象没有属性“ sections”。

Any ideas? 有任何想法吗?

It's as the error says: line is an instance of LineForm , not Line . 正如错误所言: lineLineForm的实例,而不是Line的实例。 You need to save the form object at some point to get the actual updated model instance: 您需要保存表单对象以获取实际的更新模型实例:

line_obj = line.save()

although you should probably rename the confusing line object. 尽管您可能应该重命名混乱的line对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM