Veztar
Veztar

Reputation: 39

Flask SQLAlchemy ImportError: cannot import Form

I am building a small questionnaire with Flask and SQLAlchemy, and for development testing I try to recall a random form by it's id. The terminal gives an ImportError however, but I do not have any files named after modules (like other stackoverflow problems) or circular import as the error suggests. How can I query the AddEnqueteForm in this separate file? enquete_algorithm.py:

from models import AddEnqueteForm
import random
from settings import *
from flask import request

def enq_results(form_id):
    form = AddEnqueteForm.query.all(filter=form_id)
    reliability_dict = {}
    reliability_dict['stelling_set_1'] = algorithm(form.stelling1, form.stelling2)

And of course models.py:

from main import db

class AddEnqueteForm(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    stelling1 = db.Column(db.String(4), nullable=False)
    stelling2 = db.Column(db.String(4), nullable=False)

Error:

Traceback (most recent call last):
  File "c:\Users\Enquete\enquete_algorithm.py", line 1, in <module>
    from mods import AddEnqueteForm
  File "c:\Users\Enquete\models.py", line 1, in <module>
    from main import db
  File "c:\Users\Enquete\main.py", line 9, in <module>
    from routes import *
  File "c:\Users\Enquete\routes.py", line 4, in <module>
    from models import AddEnqueteForm
ImportError: cannot import name 'AddEnqueteForm' from partially initialized module 'models' (most likely due to a circular import) (c:\Users\Enquete\models.py)

I realized some variable names are a bit confusing: the AddEnqueteForm is a model, not a form. I built the forms entirely in HTML.

Upvotes: 0

Views: 1066

Answers (1)

charchit
charchit

Reputation: 1512

The problem is not with enquete_algorithm.py .The circular import is occurs between routes.py and models.py. You are importing main.py in models.py and main.py in place imports routes.py and routes.py is importing models.py.

For solving this I made a separate file database.py where I define the db and I import db from that file in both main.py and models.py. This prevents the circular import.

database.py:

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def init_app(app):
    db.init_app(app)

models.py :

from database import db

class AddEnqueteForm(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    stelling1 = db.Column(db.String(4), nullable=False)
    stelling2 = db.Column(db.String(4), nullable=False)

In main.py you need to import both models and database and use init_app() to initialize the database.

[...]
from database import db
from models import *
[...]
app = Flask(__name__) 
database.init_app(app)

Now if you ever want to run command db.create_all() through terminal to create database. you need to use application context.

running the following commands will create the database.

from main import *
with app.app_context():
     db.create_all()

Upvotes: 2

Related Questions