DateTime checkbox will not be set by default datetime.utcnow

I am new to SQLAlchemy and could not set the DateTime to create. I tried to use the default option, which can be found in many examples. I also tried to install it manually (I commented on it). So far they have not worked. Any help would be appreciated.

models.py import datetime from flask.ext.sqlalchemy import SQLAlchemy from werkzeug import generate_password_hash, check_password_hash db = SQLAlchemy() class User(db.Model): __tablename__ = 'users' uid = db.Column(db.Integer, primary_key=True) firstname = db.Column(db.String(40)) lastname = db.Column(db.String(40)) email = db.Column(db.String(120), unique=True) created = db.Column(db.DateTime, default=datetime.datetime.utcnow()) confirmed = db.Column(db.DateTime, nullable=True) pwdhash = db.Column(db.String(100)) def __init__(self, firstname, lastname, email, password): self.firstname = firstname.title() self.lastname = lastname.title() self.email = email.lower() self.set_password(password) #self.created = datetime.datetime.utcnow() self.confirmed = None def set_password(self, password): self.pwdhash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.pwdhash, password) routes.py from tasks import app from datetime import datetime from flask import render_template, request, flash, session, url_for, redirect from forms import ContactForm, SignupForm, SigninForm from flask.ext.mail import Message, Mail from models import db, User, Tags, Tasks @app.route('/signup', methods=['GET', 'POST']) def signup(): form = SignupForm() if 'email' in session: return redirect(url_for('profile')) if request.method == 'POST': if form.validate() == False: return render_template('signup.html', form=form) else: newuser = User(form.firstname.data, form.lastname.data, form.email.data, form.password.data) db.session.add(newuser) db.session.commit() session['email'] = newuser.email return redirect(url_for('profile')) elif request.method == 'GET': return render_template('signup.html', form=form) 
+6
source share
2 answers

The problem with your default is that you call datetime.utcnow right away, and the return value (during class definition) is always used by default. You must pass the called yourself, as shown below:

 # Note the lack of parenthesis after datetime.utcnow created = db.Column(db.DateTime, default=datetime.datetime.utcnow) 

Thus, SQLAlchemy will call datetime.utcnow directly when inserting a row.

+12
source

This is also a good solution:

  created = db.Column(db.DateTime, server_default=db.func.now()) updated = db.Column(db.DateTime, server_default=db.func.now(), server_onupdate=db.func.now()) 
+2
source

All Articles