Search code examples
pythondjangodjango-modelsdjango-formslistfield

ListField not saving in Django ModelForm


I have two models in Django that contain ListFields: Polygon (and PolygonForm) and Line (and LineForm). When I get a bunch of information passed in from a user, I create new ones of these, using:

partialPolygon = Polygon(user=1001)
polygon = PolygonForm(request.POST.copy(), instance=partialPolygon)
polygon.data['line_ids'] = json.loads(polygon.data['line_ids'])
polygon.data['order'] = json.loads(polygon.data['order'])
newPoly = polygone.save()

newLine = Line(line_id=lineId, 
    point_list=line['point_list'], 
    ... 
    polygons=sect['polygons'],
    user=1001)
newLine.save()

The second method here works great. Everything is saved fine. The first works well for the most part, but always saves empty lists for the ListFields instead of the list that is passed to it. I can even do:

print polygon.data['line_ids']

and it prints out a list [u'bla bla',u'bla bla',...].

Any idea why the first method does not save lists properly? Thanks in advance!


Solution

  • When a ListField is added to a model, it needs to be told how to display as a form, and take input as a form input. In my model, I used json.loads() and json.dumps() to transfer the list into text for a form input. Therefore, when the the ModelForm took a form as an input and tried to save it, it expected a string, not a raw list.