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

Deleting an entry shows the next post, but then when using the next option on that next post, it shows the post again

So basically, when I use "view entries", it all works perfectly and shows the two original entries. Then I add an entry, and view entires goes through 3 entries. All good. Then when I delete the last entry, it deletes it and then shows me the next entry. Once again, perfect!

However, when I am on that new entry, and then choose the 'show next entry' option, it shows that entry again!

I am trying to find the area of the code that would make it behave like that, but I can't quite figure it out right away. The code should be running 'delete_entry()' and then continue to show the rest of the list accordingly.

FYI When it does the whole showing an entry twice thing, I double checked and the number of entries is normal (In other words, there are no duplicates that have been created or anything, it just behaves in a way that shows the entry twice.

Is anyone else getting this?

Here is the code for the curious:

#!/usr/bin/env python3

from collections import OrderedDict
import datetime
import sys

from peewee import *

db = SqliteDatabase('diary.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."""
    db.connect()
    db.create_tables([Entry], safe=True)

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

    if data:
        if input('Save entry? [Y/n] ').lower() != 'n':
            Entry.create(content=data)
            print("Saved successfully!")


def view_entries(search_query=None):
    """View previous entries"""
    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')
        print(timestamp)
        print('='*len(timestamp))
        print(entry.content)
        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 entires for a string."""
    view_entries(input('Search 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()    

Thanks y'all.

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