Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Forms Model Forms Save a Model Form

Simon Amz
Simon Amz
4,606 Points

Didn't understand the error message

Hi there,

Here is the error message:

1) Hmm, didn't get a 200 for the product_form view as a GET.; in my code below, i did check "if request.method == 'POST', why the error noticed "getting the view as GET"

2) Hmm, didn't find the newly-created product.; "form.save(commit=True)" should do this and register in the database, right?

3) Hmm, didn't get a redirect for the product_form view as a POST.

Here is below my code:

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render

from . import forms


def product_form(request):
    digital = models.Digital()
    form = forms.DigitalProductForm()
    if request.method == 'POST':
        form = forms.DigitalProductForm(request.POST, instance=digital)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(reverse("products:create"))
    return render(request, 'products/product_form.html', {'form': form})

3 Answers

Henrik Christensen
seal-mask
.a{fill-rule:evenodd;}techdegree
Henrik Christensen
Python Web Development Techdegree Student 38,322 Points

The problem is the digital variable - try remove it + the instance=digital since they are not required to complete the challenge.

Also, form.save(commit=True) == form.save() so there is not point in adding the commit=True :-)

Henrik Christensen
seal-mask
.a{fill-rule:evenodd;}techdegree
Henrik Christensen
Python Web Development Techdegree Student 38,322 Points

When they say Digital instance they just mean "use forms.DigitalProductForm" I think - and when the form.is_valid then it will save a new Digital instance.

Or that's how I read it :-)

Simon Amz
Simon Amz
4,606 Points

Thanks for the help that works.

I would have a last question: in the question it says: "to make the view handle saving a new Digital instance"

that's why I wrote " digital = models.Digital().

When deleting this sentence, that works but how the program does save a new DIgital instance?

Thanks for your feedback