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

(Slightly customised) code not working

Hi guys,

I've followed on from the Using Databases in Python and added and slightly tweaked the code in a replit.com server.

I'm getting the following error and can't seem to work out why. Can you help me to see where I'm going wrong.

#!/usr/bin/env python3

from collections import OrderedDict
import datetime
import sys


from peewee import *

db = SqliteDatabase('diary.db')

# Define Quant Class
class Quant(Model):
  name = TextField()
  timestamp = DateTimeField(default=datetime.datetime.now)

  class Meta:
    database = db

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

# Full List of Quants
quantsList = []

def menu_loop():
    """Show 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 you entry. Press ctrl+d when finished.")
    data = sys.stdin.read().strip()

    if data:
        if input('Save entry? [Yn] ').lower() != 'n':
            Quant.create(name=data)
            print("Saved successfully!")

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

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

        next_action = input('Action: [Nq] ').lower().strip()
        if next_action == 'q':
            break



# Expected List
Expected = "Todays's Expected"

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

if __name__ == '__main__':
    initialize()

Error Message

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 3144, in execute_sql
    cursor.execute(sql, params or ())
sqlite3.IntegrityError: NOT NULL constraint failed: quant.value

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "main.py", line 47, in add_entry
    Quant.create(name=data)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 6346, in create
    inst.save(force_insert=True)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 6556, in save
    pk = self.insert(**field_dict).execute()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 1907, in inner
    return method(self, database, *args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 1978, in execute
    return self._execute(database)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 2745, in _execute
    return super(Insert, self)._execute(database)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 2474, in _execute
    cursor = database.execute(self)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 3157, in execute
    return self.execute_sql(sql, params, commit=commit)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 3151, in execute_sql
    self.commit()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 2917, in __exit__
    reraise(new_type, new_type(exc_value, *exc_args), traceback)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 190, in reraise
    raise value.with_traceback(tb)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/peewee.py", line 3144, in execute_sql
    cursor.execute(sql, params or ())
peewee.IntegrityError: NOT NULL constraint failed: quant.value
īŗ§ 
KeyboardInterrupt

Many thanks

1 Answer

FYI this is when I'm running the add_entry() function, and it comes when I'm trying to save.

Thanks a lot