Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHarin Yuwarattanaporn
8,427 PointsI'm getting stuck here, All clue of my error I got is BUMMER! Try again. wasn't really helpful. Anyone spot my error?
I'm little confuse about g.user and _get_current_object() but I think I have done correctly.
from flask_wtf import Form
from wtforms import StringField, PasswordField, TextAreaField, DateField
from wtforms.validators import DataRequired, Email, Length
class SignUpInForm(Form):
email = StringField(validators=[DataRequired(), Email()])
password = PasswordField(validators=[DataRequired(), Length(min=8)])
class LunchOrderForm(Form):
order = TextAreaField(validators=[DataRequired()])
date = DateField(validators=[DataRequired()])
import datetime
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *
DATABASE = SqliteDatabase(':memory:')
class User(UserMixin, Model):
email = CharField(unique=True)
password = CharField(max_length=100)
join_date = DateTimeField(default=datetime.datetime.now)
bio = CharField(default='')
class Meta:
database = DATABASE
@classmethod
def new(cls, email, password):
cls.create(
email=email,
password=generate_password_hash(password)
)
class LunchOrder(Model):
order = TextField()
date = DateField()
user = ForeignKeyField(User, related_name="orders")
def initialize():
DATABASE.connect()
DATABASE.create_tables([User], safe=True)
DATABASE.close()
from flask import Flask, g, render_template, flash, redirect, url_for
from flask.ext.bcrypt import check_password_hash
from flask.ext.login import LoginManager, login_user, current_user, login_required, logout_user
import forms
import models
app = Flask(__name__)
app.secret_key = 'this is our super secret key. do not share it with anyone!'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
g.user = current_user
@app.route('/order', methods=('GET', 'POST'))
def order_lunch():
form = forms.LunchOrderForm()
if form.validate_on_submit():
models.LunchOrder.create(order=form.order.data, date=form.date.data, user=g.user._get_current_object())
return render_template('lunch.html', form=form)
@login_manager.user_loader
def load_user(userid):
try:
return models.User.select().where(
models.User.id == int(userid)
).get()
except models.DoesNotExist:
return None
@app.before_request
def before_request():
g.db = models.DATABASE
g.db.connect()
g.user = current_user
@app.after_request
def after_request(response):
g.db.close()
return response
@app.route('/register', methods=('GET', 'POST'))
def register():
form = forms.SignUpInForm()
if form.validate_on_submit():
models.User.new(
email=form.email.data,
password=form.password.data
)
flash("Thanks for registering!")
return render_template('register.html', form=form)
@app.route('/login', methods=('GET', 'POST'))
def login():
form = forms.SignUpInForm()
if form.validate_on_submit():
try:
user = models.User.get(
models.User.email == form.email.data
)
if check_password_hash(user.password, form.password.data):
login_user(user)
flash("You're now logged in!")
else:
flash("No user with that email/password combo")
except models.DoesNotExist:
flash("No user with that email/password combo")
return render_template('register.html', form=form)
@app.route('/secret')
@login_required
def secret():
return "I should only be visible to logged-in users"
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('login'))
@app.route('/')
def index():
return render_template('index.html')
2 Answers
Tatiana Vasilevskaya
Python Web Development Techdegree Graduate 28,600 PointsRemove g.user = current_user from line 13. You already correctly do this before each request (in before_request function). You code looks great otherwise!
Oziel Perez
61,321 PointsWow, unbelievable. Ok so I took a wild guess that maybe the date field needed to have a properly made date from datetime, which I took notice of because in the models file in LunchOrder, the Date field doesn't have "default = datetime.datetime.now" set up. I don't know if that was intentional or if a mistake, but in anycase, what I did was import datetime at the top of lunch.py and then in the date parameter I put "date = datetime.datetime.now()" instead of form.date.data and it worked (shouldn't it be date.today() since it's just a date field?). Can't believe this was not specified.
Tatiana Vasilevskaya
Python Web Development Techdegree Graduate 28,600 PointsMaybe you could show a code snippet? I'm not sure I fully understand what you're talking about.
Oziel Perez
61,321 PointsHere is the lunch.py file, this is what I had to do to pass:
from flask import Flask, g, render_template, flash, redirect, url_for
from flask.ext.bcrypt import check_password_hash
from flask.ext.login import LoginManager, login_user, current_user, login_required, logout_user
import forms
import models
import datetime
app = Flask(__name__)
app.secret_key = 'this is our super secret key. do not share it with anyone!'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@app.route('/order', methods=('GET', 'POST'))
def order_lunch():
form = forms.LunchOrderForm()
if form.validate_on_submit():
models.LunchOrder.create(order=form.order.data, date=datetime.datetime.now(), user=g.user._get_current_object())
return render_template('lunch.html', form=form)
@login_manager.user_loader
def load_user(userid):
try:
return models.User.select().where(
models.User.id == int(userid)
).get()
except models.DoesNotExist:
return None
@app.before_request
def before_request():
g.db = models.DATABASE
g.db.connect()
g.user = current_user
@app.after_request
def after_request(response):
g.db.close()
return response
@app.route('/register', methods=('GET', 'POST'))
def register():
form = forms.SignUpInForm()
if form.validate_on_submit():
models.User.new(
email=form.email.data,
password=form.password.data
)
flash("Thanks for registering!")
return render_template('register.html', form=form)
@app.route('/login', methods=('GET', 'POST'))
def login():
form = forms.SignUpInForm()
if form.validate_on_submit():
try:
user = models.User.get(
models.User.email == form.email.data
)
if check_password_hash(user.password, form.password.data):
login_user(user)
flash("You're now logged in!")
else:
flash("No user with that email/password combo")
except models.DoesNotExist:
flash("No user with that email/password combo")
return render_template('register.html', form=form)
@app.route('/secret')
@login_required
def secret():
return "I should only be visible to logged-in users"
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('login'))
@app.route('/')
def index():
return render_template('index.html')
just import datetime and then add datetime.datetime.now to the date parameter in the create method of the LunchOrder model
Tatiana Vasilevskaya
Python Web Development Techdegree Graduate 28,600 PointsI looked at your code. You shouldn't do date=datetime.datetime.now() when creating an order as then you override the date that user specified in the form. If makes filling the date field in the form pointless. Your code passes the challenge when you use this trick, but it is not only about passing tests in the code challenge, right?
Your code also passes with date=form.date.data. I would suggest rechecking forms.py file if you get an error when submitting the code in this variant.
Oziel Perez
61,321 PointsOziel Perez
61,321 PointsI have the same code as harin does. I did not have an extra g.user line, but it still says it's wrong and absolutely no feedback at all on what I did wrong.
Tatiana Vasilevskaya
Python Web Development Techdegree Graduate 28,600 PointsTatiana Vasilevskaya
Python Web Development Techdegree Graduate 28,600 PointsOziel, I can't say what is wrong with your code without seeing it, however, the code provided by Harin passes the challenge without the line I pointed out.
Harin Yuwarattanaporn
8,427 PointsHarin Yuwarattanaporn
8,427 PointsThanks Tatiana! That is my clumsy mistake. Anyway, I really annoy when BUMMER: TRY AGAIN appear. It doesn't give any clue!