Search code examples
pythonbottle

How to make an error page for non existent articles


How to make a error page if an article does not exist in this program? This error code only returns it if its a 404 error, where as I want it to return this template for when there's an article that does not exist that the user tries to go to.

So basically if user searches for '/wiki/x'. x being anything the user enters, if it does not exist I want to return this error template.

I can't find a lot of info on how to work with error pages in python with bottle so any help would be appreciated.

@route('/wiki/<pagename>')
def show_article(pagename):
    """Displays a single article (loaded from a text file)."""
    articles=read_articles_from_file()
    for article in articles:
        if article['title'] == pagename:
            titel = article
    return template('wiki', article = titel)
@error(404)
def error404(error):
    '''
    Funktionen ger ett felmeddelande, ifall de kommer
    till en sida som inte existerar
    '''
    return template("error")

Solution

  • You should test after finishing your loop if you found an article or not, if not render your error page like this :

    @route('/wiki/<pagename>')
    def show_article(pagename):
        """Displays a single article (loaded from a text file)."""
        articles=read_articles_from_file()
        titel = None
        for article in articles:
            if article['title'] == pagename:
                titel = article
        if titel == None:
            return template("error")
        return template('wiki', article = titel)