Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model not saving.. Totally confused here

I have the following code in my view

page = get_object_or_404(Page, site = site, slug = slug)
pagecontents = PageContent.objects.filter(page=page)
pagecontents[0].description = form.cleaned_data['description']
pagecontents[0].save()
print pagecontents[0].description
print form.cleaned_data['description']

When the two print statements execute, i get the following

for the line print pagecontents[0].description

<p>Most important page</p>

for the line form.cleaned_data['description']

<p>Least important page</p>

Why is the object not getting saved?

like image 464
arustgi Avatar asked Dec 13 '22 09:12

arustgi


1 Answers

You're not keeping the changed object.

pagecontents[0].description = form.cleaned_data['description']

This makes an object from pagecontents[0], changes description, and then loses track of the object, which gets garbage collected at some point.

pagecontents[0].save()

This makes another object from pagecontents[0] and saves it, which does nothing since it is unchanged.

pagecontents is a queryset, so it's not going to create any objects until it actually runs the query, which in this case is when you apply [0] to it.

You need to keep track of the object:

pagecontent = PageContent.objects.filter(page=page)[0]
pagecontent.description = form.cleaned_data['description']
pagecontent.save()
like image 71
Mike DeSimone Avatar answered Dec 29 '22 19:12

Mike DeSimone