4

I'm currently trying to deploy my flask application to Heroku, but I am encountering an error during database initialization.

Here is my models.py file:

from app import app  
from app import db  
from werkzeug.security import generate_password_hash, check_password_hash  
from sqlalchemy import create_engine, Column, Integer, String, Date, ForeignKey, event, Boolean, Table  
from sqlalchemy.orm import scoped_session, sessionmaker, backref, relationship  

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    password = db.Column(db.String(255), nullable=False, server_default='')
    email = db.Column(db.String(255), nullable=False, unique=True, index=True)
    confirmed_at = db.Column(db.DateTime())
    authenticated = db.Column(db.Boolean(), nullable=False, server_default='0')
    company_name = db.Column(db.String(100), nullable=False, server_default='')

    roles = db.relationship('Role')


    def __init__(self, email, company_name, password):
        self.email = email
        self.company_name = company_name
        self.set_password(password)

    def get_id(self):
        return self.email

    def is_active(self):
        #True, as all users are active.
        return True

    def is_authenticated(self):
        #"""Return True if the user is authenticated."""
        return self.authenticated

    def is_anonymous(self):
        #False, as anonymous users aren't supported."""
        return False

    def set_password(self, password):
        self.password = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password, password)

    def __repr__(self):
        return '<User %r>' % (self.company_name)

class Role(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    user_id = db.Column(db.String, db.ForeignKey('user.id'))`

Here is my db_create.py file:

#!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))

When initializing my database, I am receiving the following stack trace:

Traceback (most recent call last):
  File "db_create.py", line 7, in <module>
    db.create_all()
  File "/app/.heroku/python/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 895, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "/app/.heroku/python/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 887, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 3404, in create_all
    tables=tables)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1616, in _run_visitor
    conn._run_visitor(visitorcallable, element, **kwargs)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1245, in _run_visitor
    **kwargs).traverse_single(element)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 120, in traverse_single
    return meth(obj, **kw)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 713, in visit_metadata
    self.traverse_single(table, create_ok=True)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 120, in traverse_single
    return meth(obj, **kw)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 732, in visit_table
    self.connection.execute(CreateTable(table))
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 729, in execute
    return meth(self, multiparams, params)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 69, in _execute_on_connection
    return connection._execute_ddl(self, multiparams, params)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 783, in _execute_ddl
    compiled
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 958, in _execute_context
    context)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1159, in _handle_dbapi_exception
    exc_info
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 951, in _execute_context
    context)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 436, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) column "id" referenced in foreign key constraint does not exist
 '\nCREATE TABLE role (\n\tid SERIAL NOT NULL, \n\tname VARCHAR(100), \n\tuser_id VARCHAR, \n\tPRIMARY KEY (id), \n\tFOREIGN KEY(user_id) REFERENCES "user" (id)\n)\n\n' {}

Does anyone know what is causing this?

Thanks!

0

1 Answer 1

5

Type mismatch problem: You defined the foreign key as String type for Role table:

user_id = db.Column(db.String, db.ForeignKey('user.id'))

while it's Integer in User table:

id = db.Column(db.Integer, primary_key=True).

Change one of them so two fields (Field name and the Foreign Field name) are using compatible field type.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this worked! Unfortunately I don't have enough reputation to give you a vote :(
@JohnLopez Glad it helped, you can just accept my answer :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.