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 Our Diary App Initialize Database & Create Tables

Munesh Raj Lakhey
Munesh Raj Lakhey
4,408 Points

Do not understand the following tracebacke error in my diary.py

Traceback (most recent call last):                                                                                                              
  File "diary.py", line 107, in <module>                                                                                                        
    menu_loop()                                                                                                                                 
  File "diary.py", line 45, in menu_loop                                                                                                        
    menu[choice]()                                                                                                                              
  File "diary.py", line 55, in add_entry                                                                                                        
    Entry.create(content=data)  

Here is the code:

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

# in console start with - chmod +x diary.py

db = SqliteDatabase('diary.db')



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

  class Meta:
    database=db


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


def clear():
  os.system('cls' if os.name=='nt' else 'clear')

def menu_loop():
      """nothing yet"""
      choice = None

      while choice != 'q':
        clear()
        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:
          clear()
          menu[choice]()

def add_entry():
  """Add an entry"""
  print("Enter you stuffs. Press ctrl+d when done.")
  data = sys.stdin.read().strip()

  if data:
    try:
      if input('Save Entry? [Yn]  ').lower() != 'n':
        Entry.create(content=data)
        print("saved successfully!")

    except EOFError:
      print("save aborted!")



def view_entries(search_query=None):
  """View the items"""
  entries = Entry.select().order_by(Entry.timestamp.desc())
  if search_query:
    entries = entries.where(Entry.content.contains(search_query))

  for entry in entries:
    timestamp = Entry.timestamp.strftime('%A %B %d, %Y %I:%M%p')
    clear()
    print(timestamp)
    print('='*len(timestamp))
    print(entry.content)
    print('\n\n'+'='*len(timestamp))
    print('n) next entry')
    print('d) delete entry')
    print('q) return to main menu')

    next_action = input('Action: [ndq] ').lower().strip()
    if next_action == 'q':
      break
    elif next_action == 'd':
      delete_entry(entry)


def search_entries():
  """Search entries for a string"""
  view_entries = input("seaech query: ")


def delete_entry(Entry):
  """delete an Entry"""
  if input("Are you sure [yN]").lower()=='y':
    entry.delete_instance()
    print("Entry deleted" )

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


if __name__== '__main__':
  initialize()
  menu_loop()

[MOD: added ```python markdown formatting -cf]

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Can you please post the full stacktrace? The actual error isn't mentioned above.

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

i wasn't able to reproduce your exact error, but I found the following error. In the code, you reference Entry instead of of the for-loop variable entry. This raise the following error:

Traceback (most recent call last):
  File "diary.py", line 106, in <module>
    menu_loop()
  File "diary.py", line 44, in menu_loop
    menu[choice]()
  File "diary.py", line 69, in view_entries
    timestamp = Entry.timestamp.strftime('%A %B %d, %Y %I:%M%p')

In can be fixed using:

    for entry in entries:
        timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p')   # <-- changed to 'entry'
Munesh Raj Lakhey
Munesh Raj Lakhey
4,408 Points

Thanks a lot for helping out. After changing when I tried to save, I got this error msg.

Traceback (most recent call last):
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2780, in execute_sql
cursor.execute(sql, params or ())
sqlite3.OperationalError: table entry has no column named content

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "diary.py", line 107, in <module>
menu_loop()
File "diary.py", line 45, in menu_loop
menuchoice
File "diary.py", line 55, in add_entry
Entry.create(content=data)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 3587, in create
inst.save(force_insert=True)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 3719, in save
pk_from_cursor = self.insert(**field_dict).execute()
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/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.5.0/lib/python3.5/site-packages/peewee.py", line 2172, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2788, in execute_sql
self.commit()
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2657, in __exit
_
reraise(new_type, new_type(*exc_value.args), traceback)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 115, in reraise
raise value.with_traceback(tb)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2780, in execute_sql
cursor.execute(sql, params or ())
peewee.OperationalError: table entry has no column named content

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

A table entry error is usually due to a change between the model and the database. While you could manually try to add the content column to the entry table, in quick development it is sometimes easier to simply delete the database file diary.db and let the code auto-recreated it for you with the correct columns.