简体   繁体   中英

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. My code looks something like:

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

I get the error:

'LineForm' object has no attribute 'sections'.

Any ideas?

It's as the error says: line is an instance of LineForm , not 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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