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 Display a Blank Model Form

Calum Devitt
Calum Devitt
3,763 Points

Model Forms question

I'm kinda stuck on this question, can someone guide me please? question is: We've made models and model forms, now we need a view to render the form. Write a new view named product_form that instantiates the DigitalProductForm and provides it to the products/product_form.html template as the key "form".

products/views.py
from django.shortcuts import render, get_object_or_404

from . import forms

def product_form(request):
    form = get_object_or_404(models.DigitalProductForm)
    if request.method == 'POST':
        form = forms.DigitalProductsForm(request.POST)
        if form.isValid():
            form.save()
    return render(request, 'products/product_form.html ', {'form': form} )
products/templates/products/product_form.html
<form action='' method='POST'>
    <input type="submit" value="Save">
</form>

1 Answer

Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Hello Calum.

I think you have gone way too far here. Please read the instruction carefully because you have written a lot of unnecessary code. There is no indication (in the code challenge) that you have to check if the form validates or if the request method is POST...

All you need is basically the first line inside the function plus the return statement but that is correct.

Regarding the line that instantiate the form: there is no need to import get_object_or_404 as you don't really need to use it here. all you have to do is

form = forms.DigitalProductForm

At this point you will have the form to send to the template with the last line of your code.

Let me know if it is clear ;) Vitto