1

Im following a youtube tutorial on using Flask and when i run this code by using python -m flask run it shows this AttributeError: 'SQLAlchemy' object has no attribute 'datetime'. How can I fix it?

from flask import Flask, render_template, url_for
from flask_sqlalchemy import SQLAlchemy

from datetime import datetime as dt

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(200), nullable=False)
    date_created = db.Column(db.datetime, default=datetime.utcnow)

    def __repr__(self):
        return '<Task %r' % self.id

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == "__main__":
    app.run(debug=True)
Wayne
  • 15
  • 1
  • 4
  • please show full traceback – luigigi Jun 08 '20 at 12:35
  • the traceback is very long that when I try to add the full part, it is requiring me to add more details. But last few lines look like this File "C:\Users\home\PycharmProjects\Flaskintroduction\app.py", line 11, in class Todo(db.Model): File "C:\Users\home\PycharmProjects\Flaskintroduction\app.py", line 14, in Todo date_created = db.Column(db.datetime, default=datetime.utcnow) AttributeError: 'SQLAlchemy' object has no attribute 'datetime' – Wayne Jun 08 '20 at 13:03
  • Does this answer your question? [SQLALchemy adds significant overload. SQLAlchemy Object has no attribute 'dateTime](https://stackoverflow.com/questions/57424146/sqlalchemy-adds-significant-overload-sqlalchemy-object-has-no-attribute-dateti) – noslenkwah Jun 08 '20 at 13:55
  • oh yes it works thank you – Wayne Jun 08 '20 at 14:19

1 Answers1

3

Column types are classes and capitalized. Try this:

db.Column(db.DateTime, default=datetime.utcnow)

Notice DateTime, not datetime.

Ken Kinder
  • 12,654
  • 6
  • 50
  • 70