Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask DateTime won't set with default datetime.utcnow [duplicate]

I am new to SQLAlchemy and have been unable to set the DateTime for created. I have tried using the "default" option found in many examples. I have also tried setting it manually (I have it commented out). Neither have worked so far. 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)
like image 511
Ethan Avatar asked Jan 05 '14 08:01

Ethan


1 Answers

The problem with your default is that you're calling datetime.utcnow immediately there, and the value returned (at the time of class definition) is always used as default. You need to pass the callable itself like following:

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

This way SQLAlchemy will call datetime.utcnow itself upon row insert.

like image 164
Audrius Kažukauskas Avatar answered Oct 13 '22 08:10

Audrius Kažukauskas