Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Using Databases in Python Gettin' CRUD-y With It Add An Entry

Jonathan Fernandes
PLUS
Jonathan Fernandes
Courses Plus Student 22,784 Points

Error raised when trying to save the entry

So I am working on workspaces and following along. After I watched this video, I tried to run it.

Everything works including pressing 'n' to cancel, but when I try to hit a key to continue, I get this error:

Traceback (most recent call last):                                                                                               
  File "7_add-entry.py", line 67, in <module>                                                                                    
    menu_loop()                                                                                                                  
  File "7_add-entry.py", line 36, in menu_loop                                                                                   
    menu[choice]()                                                                                                               
  File "7_add-entry.py", line 47, in add_entry                                                                                   
    Entry.create(contents=data)                                                                                                  
  File "/usr/local/pyenv/versions/3.4.1/lib/python3.4/site-packages/peewee.py", line 3587, in create                             
    inst.save(force_insert=True)                                                                                                 
  File "/usr/local/pyenv/versions/3.4.1/lib/python3.4/site-packages/peewee.py", line 3719, in save                               
    pk_from_cursor = self.insert(**field_dict).execute()                                                                         
  File "/usr/local/pyenv/versions/3.4.1/lib/python3.4/site-packages/peewee.py", line 2610, in execute                            
    return self.database.last_insert_id(self._execute(), self.model_class)                                                       
  File "/usr/local/pyenv/versions/3.4.1/lib/python3.4/site-packages/peewee.py", line 2172, in _execute                           
    return self.database.execute_sql(sql, params, self.require_commit)                                                           
  File "/usr/local/pyenv/versions/3.4.1/lib/python3.4/site-packages/peewee.py", line 2788, in execute_sql                        
    self.commit()                                                                                                                
  File "/usr/local/pyenv/versions/3.4.1/lib/python3.4/site-packages/peewee.py", line 2657, in __exit__                           
    reraise(new_type, new_type(*exc_value.args), traceback)                                                                      
  File "/usr/local/pyenv/versions/3.4.1/lib/python3.4/site-packages/peewee.py", line 115, in reraise                             
    raise value.with_traceback(tb)                                                                                               
  File "/usr/local/pyenv/versions/3.4.1/lib/python3.4/site-packages/peewee.py", line 2780, in execute_sql                        
    cursor.execute(sql, params or ())                                                                                            
peewee.IntegrityError: entry.content may not be NULL

Don't understand what is going on... please help.

[edit: formatting. --cf]

Jonathan Fernandes
Jonathan Fernandes
Courses Plus Student 22,784 Points

Just exported my file to the command shell for my windows machine, and it raises the same error...

Is this because I am using a conflicting version of Python?

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,986 Points

The traceback can be overwhelming, the key lines are:

  File "7_add-entry.py", line 47, in add_entry                                                                                   
    Entry.create(contents=data)                                                                                                  

and

peewee.IntegrityError: entry.content may not be NULL

This is saying peewee is trying to create a new database entry for "Entry", but the data value provide in contents=data is NULL which violates a data integrity check performed by peewee ("may not be NULL") prior to writing the database.

The issue is why does data have a NULL value? Without seeing your code it's hard to guess. I suggest looking for code paths that do not initiate or use an uninitiated value for data.

EDIT: Looking again at your code, I see the error more clearly.

In your code you are creating the new entry with:

Entry.create(contents=data)

However, the field name defined in the class Entry is "content" not "content*s*". It is complaining because you are setting contents, but no value is being assigned to content and is therefore NULL which raises the error.

Jonathan Fernandes
PLUS
Jonathan Fernandes
Courses Plus Student 22,784 Points

Hmm... not sure either...

One moment, I'll post my code:

#!/usr/bin/env python3
from collections import OrderedDict
import datetime
import sys

from peewee import *  #notice third library imports are here and python's libraries are grouped together (good convention)

db = SqliteDatabase('journal.db')


class Entry(Model):
    content = TextField()
    timestamp = DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = db


def initialize():
    """Create the database and the table if they don't exist already."""
    db.connect()
    db.create_tables([Entry], safe=True)


def menu_loop():
    """show me the menu"""
    choice = None

    while choice != 'q':
        print('Enter "q" to quit')
        for key, value in menu.items():
            print('{}) {}'.format(key, value.__doc__))
        choice = input('Action: ').lower().strip()

        if choice in menu:
            menu[choice]()


def add_entry():
    """Add an entry."""
    print("Enter your entry and then press ctrl+D (ctrl+Z for windows users) when you are finished.")
    data = sys.stdin.read().strip()  #this reads what is on the screen and we strip it of surrounding white space

    #now we check to make sure they actually entered something
    if data:
        if input("Save entry?  [Press 'N' to cancel, press 'Enter' to continue]  ").lower() != 'n':
            Entry.create(contents=data)
            print("Your entry has been saved!")


def view_entries():
    """View previous entries."""


def delete_entry(entry):
    """Delete an entry."""


menu = OrderedDict([
    ('a', add_entry),
    ('v', view_entries),
])


if __name__ == '__main__':
    initialize()
    menu_loop()
Jonathan Fernandes
Jonathan Fernandes
Courses Plus Student 22,784 Points

It's always the little things... This is why people always work in teams is my assumption! Hahaha, thanks again!