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 trialMUZ141110 Bryan Bera
3,943 PointsTacocat Challenge
I'm getting "Bummer! Try again!" error when I run my code for the Tacocat Challenge. I don't know what I'm doing wrong. Here's the code below:
code for tacocat.py:
import datetime
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *
DATABASE = SqliteDatabase('tacocat.db')
class User(UserMixin, Model):
"""A taco cat customer"""
username = CharField(unique=True)
email = CharField(unique=True)
password = CharField(max_length=100)
is_admin = BooleanField(default=False)
class Meta:
database = DATABASE
@classmethod
def create_user(cls, username, email, password, admin=False):
try:
with DATABASE.transaction():
cls.create(
username=username,
email=email,
password=generate_password_hash(password),
is_admin=admin)
except IntegrityError:
raise ValueError("User already exists")
class Taco(Model):
"""Taco creation by the customer"""
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(
rel_model=User,
related_name='tacos'
)
protein = CharField(max_length=100)
cheese = BooleanField()
shell = CharField(max_length=100)
extras = TextField()
class Meta:
database = DATABASE
order_by = ('-timestamp',)
def initialize():
DATABASE.connect()
DATABASE.create_tables([User, Taco], safe=True)
DATABASE.close()
#code for forms.py
from flask_wtf import Form
from wtforms import StringField, PasswordField, TextAreaField, BooleanField
from wtforms.validators import (DataRequired, Regexp, ValidationError, Email,
Length, EqualTo)
from models import User
def name_exists(form, field):
"""Register fails because it is a username that already exists in the database"""
if User.select().where(User.username == field.data).exists():
raise ValidationError('User with that name already exists.')
def email_exists(form, field):
"""Register fails because it is an email that already exists in the database"""
if User.select().where(User.email == field.data).exists():
raise ValidationError('User with that email already exists.')
class RegisterForm(Form):
"""Creates a form to register a new user"""
username = StringField(
'Username',
validators=[
DataRequired(),
Regexp(
r'^[a-zA-Z0-9_]+$',
message=("Username should be one word, letters, "
"numbers, and underscores only.")
),
name_exists
])
email = StringField(
'Email',
validators=[
DataRequired(),
Email(),
email_exists
])
password = PasswordField(
'Password',
validators=[
DataRequired(),
Length(min=2),
EqualTo('password2', message='Passwords must match')
])
password2 = PasswordField(
'ConfirmPassword',
validators=[DataRequired()]
)
class LoginForm(Form):
"""Creates a form to log a user in"""
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
class TacoForm(Form):
"""Creates a form to order a taco"""
protein = StringField("Meat? Chicken? Pork? Veggie?", validator=[DataRequired()])
cheese = BooleanField("Cheese", default=True)
shell = StringField("Corn? Wheat? Crispy? Soft?", validator=[DataRequired()])
extras = TextAreaField("Anything else?", validator=[DataRequired()])
#code for models.py
import datetime
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *
DATABASE = SqliteDatabase('tacocat.db')
class User(UserMixin, Model):
"""A taco cat customer"""
username = CharField(unique=True)
email = CharField(unique=True)
password = CharField(max_length=100)
is_admin = BooleanField(default=False)
class Meta:
database = DATABASE
@classmethod
def create_user(cls, username, email, password, admin=False):
try:
with DATABASE.transaction():
cls.create(
username=username,
email=email,
password=generate_password_hash(password),
is_admin=admin)
except IntegrityError:
raise ValueError("User already exists")
class Taco(Model):
"""Taco creation by the customer"""
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(
rel_model=User,
related_name='tacos'
)
protein = CharField(max_length=100)
cheese = BooleanField()
shell = CharField(max_length=100)
extras = TextField()
class Meta:
database = DATABASE
order_by = ('-timestamp')
def initialize():
DATABASE.connect()
DATABASE.create_tables([User, Taco], safe=True)
DATABASE.close()
Chris Freeman
Treehouse Moderator 68,454 PointsAre you still having issues with Tacocat?
1 Answer
Chris Adamson
132,143 PointsThis is a relatively complex challenge (compared to other one's on the website), here's a sample tacocat.py:
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, logout_user, login_required, current_user
import forms
import models
app = Flask(__name__)
app.secret_key = 'auoesh.bouoastuh.43,uoausoehuosth3ououea.auoub!'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(userid):
try:
return models.User.get(models.User.id == userid)
except models.DoesNotExist:
return None
@app.before_request
def before_request():
"""Connect to the database before each request."""
g.user = current_user
@app.route('/login', methods=('GET', 'POST'))
def login():
form = forms.LoginForm()
if form.validate_on_submit():
try:
user = models.User.get(models.User.email == form.email.data)
except models.DoesNotExist:
flash("Your email or password doesn't match!", "error")
else:
if check_password_hash(user.password, form.password.data):
login_user(user)
flash("You've been logged in!", "success")
return redirect(url_for('index'))
else:
flash("Your email or password doesn't match!", "error")
return 'add a new taco<br>log out'
@login_required
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/register', methods=('GET', 'POST'))
def register():
form = forms.RegisterForm()
if form.validate_on_submit():
flash("Yay, you registered!", "success")
models.User.create_user(
username=form.username.data,
email=form.email.data,
password=form.password.data
)
return redirect(url_for('index'))
return redirect(url_for('index'))
@app.route('/')
def index():
return 'add a new taco<br>no tacos yet<br>sign up<br>log in<br>log out'
@app.route('/taco', methods=('GET', 'POST'))
def taco():
form = forms.TacoForm()
if form.validate_on_submit():
flash("Yay, you registered!", "success")
models.Taco.create_taco(
protein=form.protein.data,
shell=form.shell.data,
extras=form.extras.data,
user=g.user.id
)
return redirect(url_for('index'))
return redirect(url_for('index'))
Chris Freeman
Treehouse Moderator 68,454 PointsChris Freeman
Treehouse Moderator 68,454 PointsHey Bryan, Your code seems to missing the main
tacocat.py
. It looks likemodels.py
was posted twice.Can you post your
tacocat.py
code?