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 Using Databases in Python Gettin' CRUD-y With It CRUD: Create Function

Eran Artzi
Eran Artzi
4,280 Points

I'm trying to complete this Python db challenge

I've created inside the function new_challenge as an instance of Challenge by doing so: new_challenge = Challenge()

and than assigned the different arguments of the function

What am I doing wrong?

crud.py
from models import Challenge

def create_challenge(name, language, steps=1):
  new_challenge = Challenge()
  new_challenge.name = name
  new_challenge.language = language
  new_challenge.steps = steps

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Hey Eran,

I wouldn't say you are doing anything wrong. Your code is missing one crucial step: the save!

from models import Challenge

def create_challenge(name, language, steps=1):
  new_challenge = Challenge()
  new_challenge.name = name
  new_challenge.language = language
  new_challenge.steps = steps
  new_challenge.save()  # <-- you gotta save it!

Ken Alger's solution, using the class create() method, is correct and the more common style to use when creating a new instance that you want to save immediately to the database. The create() method calls __init__ and save() for you.

There are times when you do not want to immediate save the instance to the database, such as, when working with Django forms. or if you need to perform additional initialization not covered in the class constructor __init__() method. In these cases, as you did, you can create a local instance, adjust the attributes, then call the class save() method.

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Eran;

In the course there is an example of creating a Student using the create() method. We can do something similar here to create a Challenge.

from models import Challenge

def create_challenge(name, language, steps=1):
  Challenge.create(name=name, language=language, steps=steps)

Post back if you are still stuck or have additional questions.

Happy coding,
Ken