Hello Coders!
This short article explains how to fix "Cannot import name TextField from wtforms" error that recently bumped after WTForms library update to version 3.x. For newcomers, WTForms is a flexible forms validation and rendering library for Python/Flask web development. It can work with whatever web framework and template engine you choose. It supports data validation, CSRF protection, internationalization (I18N).
Thanks for reading! - Content provided by App Generator.
Error Text
In case your legacy app uses WTForms without an explicit version in requirements.txt
file (like me) the next compilation might lead to a runtime error in case TextField type provided by the concerned library occurs somewhere in the codebase.
from wtforms import TextField
>> ImportError: cannot import name 'TextField' from 'wtforms'
The above error occurs when the TextField
property is used with WTForms version 3.0
or above because the wtforms.TextField
deprecated in favor of wtforms.StringField
.
How to fix it
Solution 1 - Replace
TextField
type withStringField
Note: This solution works with WTForms 3.x and 2.x versions
from wtforms import StringField
// replace all TextField usages with StringField type
Solution 2 - Use the latest stable 2.x version of WTForms
// Use 2.x version
pip install WTForms==2.3.3
Using an older version provides a quick fix for your codebase but is not recommended in the long run.
Free Sample
For this open-source sample, I've used the 2nd solution where the Cannot import name TextField from wtforms error is solved by freezing the WTForms version in requirements.txt file, without a codebase update.
- π Datta Able Flask - Source Code
- π Datta Able Flask - LIVE deployment
Thanks for reading! For more resources, please access:
Oldest comments (8)
I will check it!
Thanks for sharing
ππ
First solution sounds better in the long run.
Thank you for your work.
ππ
Thanks for sharing! You saved me.
ππ
Excellent. Thanks for sharing. I didn't know what was happening.
In the event that someone needs more detail, I attach the installation process and import test. I agree the best thing is to migrate to the latest version.
(myvirtualenv) 10:59 ~/mysite $ pip install WTFORMS==2.3.3
Looking in links: /usr/share/pip-wheels
Collecting WTFORMS==2.3.3
Downloading WTForms-2.3.3-py2.py3-none-any.whl (169 kB)
|ββββββββββββββββββββββββββββββββ| 169 kB 8.8 MB/s
Requirement already satisfied: MarkupSafe in /home/doxadocto/.virtualenvs/myvirtualenv/lib/python3.
8/site-packages (from WTFORMS==2.3.3) (2.1.0)
Installing collected packages: WTFORMS
Attempting uninstall: WTFORMS
Found existing installation: WTForms 3.0.1
Uninstalling WTForms-3.0.1:
Successfully uninstalled WTForms-3.0.1
Successfully installed WTFORMS-2.3.3
(myvirtualenv) 11:00 ~/mysite $ python
Python 3.8.5 (default, Jan 27 2021, 15:41:15)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
ππ