无法将 WTForm 类从一个文件导入到另一个文件

问题描述 投票:0回答:1

我无法将 NamerForm 从 forms.py 导入到controllers.py。获得

ImportError

导入错误:无法从

NamerForm
 导入 
application.forms

文件目录结构:

.venv
|____applications
   |-__init__.py
   |-config.py
   |-controllers.py
   |-forms.py
|____templates
   |-name.html
|____static
|____main.py

main.py

from flask import Flask
import os, application.config
from application.config import LocalDevelopmentConfig
from application.database import db


app = None

def create_app():
     app = Flask(__name__, template_folder='templates', static_folder='static')
     app.config['SECRET_KEY']='somekey'
     if os.getenv('ENV',"development") == "production":
          raise Exception("Currently no production config is set up.")
     else:
          print("Starting Local Development")
          app.config.from_object(LocalDevelopmentConfig)
     db.init_app(app)
     app.app_context().push()

     return(app)

app = create_app()


from application.controllers import *
if __name__ == '__main__':
     app.run(host='127.0.0.1', port=8080)

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

class NamerForm(FlaskForm):
     name = StringField("write something", validators=[DataRequired()])
     submit = SubmitField("Submit")

控制器.py

from flask import Flask,render_template, url_for
from flask import current_app as app
#from app import app
from .forms import NamerForm

#---other app routes--------

@app.route("/name", methods = ['GET', 'POST'])
def name():
     name = None
     form = NamerForm()
     if form.validate_on_submit():
         name = form.name.data
         form.name.data = ''
     return(render_template("name.html", name = name, form = form))

请注意,如果没有“名称”功能,应用程序运行时不会出现错误。

flask flask-sqlalchemy flask-wtforms
1个回答
0
投票

您应该重命名文件夹或将导入名称更改为应用程序。但是,重命名文件夹是一种更好的方法,因为根据

Flask 模式
,正确的文件夹名称是
application
app

我通过更改文件夹名称测试了您的代码,它有效。

© www.soinside.com 2019 - 2024. All rights reserved.