64

Cannot import name 'TextField' from 'wtforms'

 2 years ago
source link: https://dev.to/sm0ke/cannot-import-name-textfield-from-wtforms-58n8
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cover image for Cannot import name 'TextField' from 'wtforms'
Sm0ke

Posted on Nov 8

• Originally published at docs.appseed.us

Cannot import name 'TextField' from 'wtforms'

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'
Enter fullscreen modeExit fullscreen mode

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 with StringField

Note: This solution works with WTForms 3.x and 2.x versions

from wtforms import StringField
// replace all TextField usages with StringField type 
Enter fullscreen modeExit fullscreen mode

Solution 2 - Use the latest stable 2.x version of WTForms

// Use 2.x version
pip install WTForms==2.3.3
Enter fullscreen modeExit fullscreen mode

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.


Cannot import name TextField from wtforms - Free sample for the fix.


Thanks for reading! For more resources, please access:


  • WTForms - official documentation
  • Flask - library documentation
  • Join the AppSeed community on Discord and connect to other fellow developers.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK