Python error ImportError: cannot import name Markup from jinja2
occurs when you import the Markup
class on the latest jinja2
module version.
This is because Jinja2 has refactored and moved the Markup
class to the MarkUpSafe module when version 3.10.0 was released.
Solving ImportError: cannot import name Markup from jinja2
On Jinja2 previous versions, you can import the Markup
class as shown below:
from jinja2 import Markup
But after version 3.10.0, the import
statement above will cause the following error:
Traceback (most recent call last):
File ...
from jinja2 import Markup
ImportError: cannot import name 'Markup' from 'jinja2'
To fix this error, you need to redirect the import from jinja2
to markupsafe
like this:
from markupsafe import Markup
With that, you should be able to use the Markup
class in your code.
Alternatively, you can also downgrade your jinja2
version to 3.0.3, which is the latest jinja2
version that supports importing the Markup
class.
Use one of the following pip
commands to downgrade your jinja2
module:
pip install jinja2==3.0.3 --force-reinstall
# for pip3:
pip3 install jinja2==3.0.3 --force-reinstall
With that, importing Markup
from jinja2
will not produce an error.
Handling Markup error in Flask
The Flask framework for Python relies on Jinja2 for its template engine.
You may see the same error when you run a Flask application. To fix it, you need to upgrade your Flask application to the latest version:
pip install flask --upgrade
#or
pip3 install flask --upgrade
Once you upgraded the Flask module, the application should be able to run without encountering this error.
Conclusion
Python shows ImportError: cannot import name Markup from jinja2
when you try to import the Markup
class from jinja2
module.
To fix this error, you need to import the Markup
class from markupsafe
module.
Hope this tutorial helps. Cheers! 🍻