Common errors on Flask and how to fix them

Endrit Qerreti

Endrit Qerreti

In this tutorial, we will go through the most common errors that happens on Flask, explain what causes them and also explain how to fix them.

Error : SyntaxError: trailing comma not allowed without surrounding parentheses

This error happens when a comma is added after the import line on flask. For example, this import will produce the above error

Invalid import

from flask import Flask,

To fix this error, remove the comma from flask and try again

Valid import

from flask import Flask

Error : ImportError: cannot import name 'Flasks' from 'flask' (/home/owlhowto/.local/lib/python3.10/site-packages/flask/init.py)

If you are getting the above error when you try to run your flask app, this means that flask couldn't be imported. Make sure that there is no additional character when importing flask, for example this import will give you the above error

Invalid import

from flask import Flasks

Notice Flasks is misspelled, any character or symbol will make the import invalid, so make sure that the module that you are importing it's not misspelled

Valid import

from flask import Flask

Error

Traceback (most recent call last):
  File "/home/owlhowto/flask/flaskproject.py", line 10, in <module>
    def index_page():
  File "/home/owlhowto/.local/lib/python3.10/site-packages/flask/scaffold.py", line 436, in decorator
    self.add_url_rule(rule, endpoint, f, **options)
  File "/home/owlhowto/.local/lib/python3.10/site-packages/flask/scaffold.py", line 51, in wrapper_func
    return f(self, *args, **kwargs)
  File "/home/owlhowto/.local/lib/python3.10/site-packages/flask/app.py", line 1052, in add_url_rule
    rule = self.url_rule_class(rule, methods=methods, **options)
  File "/home/owlhowto/.local/lib/python3.10/site-packages/werkzeug/routing/rules.py", line 457, in __init__
    raise ValueError("urls must start with a leading slash")
ValueError: urls must start with a leading slash

This error happens when @app.route is not defined. To fix this error you need to define routing

Invalid syntax

@app.route('')

Valid syntax

@app.route('/')

Error

@app.route("\")
               ^
SyntaxError: unterminated string literal

This error happens when you are using the wrong backslash for routing. To fix this error, simply replace \ with / on the @app.route('/')

Correct syntax

@app.route("/")

Error : NameError: name 'render_template' is not defined

This error happens when you are using the render_template function on your code, but you haven't imported the function.

To fix this issue, you need to import render_template on your flask project before calling it

import render_template

Error : RuntimeError: Working outside of application context

Traceback (most recent call last):
  File "/home/owlhowto/flask/flaskproject.py", line 19, in <module>
    render_template('function.html')
  File "/home/owlhowto/.local/lib/python3.10/site-packages/flask/templating.py", line 149, in render_template
    app = current_app._get_current_object()  # type: ignore[attr-defined]
  File "/home/owlhowto/.local/lib/python3.10/site-packages/werkzeug/local.py", line 508, in _get_current_object
    raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.

The cause of the error above is when the return function is not called correctly. For example, if you try to execute the code below you will get the same error, because the return function has nothing to return.

app.route("/function")
def function():
    
    return 
render_template('function.html')

To fix this error, you need to call the function return correctly, as shown in the code below

app.route("/function")
def function():
    
  
return render_template('function.html')v

Error : NameError: name 'app' is not defined. Did you mean: 'app2'?

This error happens when you are calling the object app but this object it's not defined. The reason why it says "Did you mean app2?" is because flask name is defined on the object called app2 as shown in the example code below.

app2 = Flask(__name__)

if __name__ == '__main__':
    app.debug = True
    app.run()

To fix this error, make sure that defined objects is the same with the function that you are calling

app = Flask(__name__)

if __name__ == '__main__':
    app.debug = True
    app.run()

Error : jinja2.exceptions.TemplateNotFound: index.html

This error happens when the template that you are trying to render doesn't exist. The template that we are trying to render is called index.html.

Make sure that the template you want to render does exist, and that there are no misspelling mistakes, for example to reproduce this error you can try to render a template that is not valid.

Error

Traceback (most recent call last):
  File "/home/owlhowto/flask/flaskproject.py", line 23, in <module>
    app.debug = true
NameError: name 'true' is not defined. Did you mean: 'True'?

This error happens when app.debug is set to lowercase true. This is wrong because flask is case sensitive, so true and True even though it's the same word, the lowercase doesn't work on flask.

if __name__ == '__main__':
    app.debug = true
    app.run()

To fix this error, simply replace true with True and the error should be gone.

if __name__ == '__main__':
    app.debug = True
    app.run()

Error

werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'sstatic' with values ['filename']. Did you mean 'static' instead?

This error happens when the function url_for() is trying to access a folder that doesn't exist, in our case the folder static exists, but the word static is misspelled.

<link rel="stylesheet" type="text/css" href="{{ url_for('sstatic', filename='main.css') }}">

To fix this issue simply fix the misspelled word static in the url_for() function.

Error

jinja2.exceptions.TemplateSyntaxError: tag name expected

This error happens when you are using two % when opening and closing the blocks, which is not a correct syntax, because you need to use only one % on blocks.

Invalid syntax

{%% block main %%}
{%% endblock %%}

Valid syntax

{% block main %}
{% endblock %}

Error

jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.

This error happens when the {% endblock %} is missing from your code. This means the block is not closed and that's why you are getting the above error.

To fix this error, simply close the block using {% endblock %}

Conclusion

In this tutorial, you learned how to fix the most common errors when using flask and python.