Reputation: 184
I am working on a flask project. The structure of the project is as follows:
├── project
│ ├── config.py
│ ├── __init__.py
│ ├── models.py
│ ├── main
│ ├── static
│ ├── templates
│ └── users
└── run.py
run.py
from project import create_app
app = create_app()
if __name__=="__main__":
app.run(debug=True)
__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from project.config import Config
db = SQLAlchemy()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
from project.main.routes import main
from project.users.routes import users
app.register_blueprint(main)
app.register_blueprint(users)
return app
models.py
from flask import current_app
from project import db
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.image_file}')"
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Post('{self.title}', '{self.date_posted}')"
My problem is when I open the terminal in project/project
directory and open a python prompt and import Users or Post from models.py, it gives me the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/aman/Desktop/websites/project/project/models.py", line 2, in <module>
from project import db
ModuleNotFoundError: No module named 'project'
But it's clear that project does exist and is also a python module since, I have created a init.py file in project directory. Please help me.
Upvotes: 1
Views: 12395
Reputation: 184
At last I have found that I was trying to import db and Users from inside the project module. When I tried to access db and Users from outside directory of project modules, I finally succeed.
Initial directory I am importing db:
/home/aman/Desktop/websites/project/project
which gives error.
Now, directory I am importing db:
/home/aman/Desktop/websites/project
which works good.
Upvotes: 2