pl-jay
pl-jay

Reputation: 1100

Cannot import python class from another directory

Here i have following directory structure,

src/models/UserModel.py
src/resources/UserResources.py

and UserModel.py contains

from datetime import datetime
from run import db
from passlib.hash import pbkdf2_sha256 as sha256
from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, ForeignKey
from flask import jsonify


class UserModel(db.Model):
    __tablename__ = 'users'

    id            = db.Column(db.Integer, primary_key = True)
    username      = db.Column(db.String(120), unique = True, nullable = False)
    password      = db.Column(db.String(120), nullable = False)
    user_role     = db.Column(db.String(10), nullable = False)
    access_token  = db.Column(db.String(120), unique = True, nullable = True)
    refresh_token = db.Column(db.String(120), unique = True, nullable = True)

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

and UserResources.py file imports UserModel like this from models import UserModel

even though the models directory having the __init__.py file, it raises the following error ImportError: cannot import name 'UserModel' from 'models'

What I'm doing wrong here ?

Upvotes: 0

Views: 73

Answers (1)

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

Try using:

from src.models.UserModel import UserModel

Upvotes: 1

Related Questions