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 trial

Python Build a Social Network with Flask Tacocat Challenge Tacocat!

Chris Grazioli
Chris Grazioli
31,225 Points

Why is my code not passing the Tacocat challenge. The grader is less than helpful, only spitting back Bummer! Try again!

I can't seem to find what I'm missing for the grader. I've commented out he app.run() call. The code passes the app_tests.py with what looks like a warning for deprecated code, but I still get an OK

tacocat.py
from flask import (Flask, g, render_template, flash,
                   redirect, url_for, abort)
from flask.ext.login import (LoginManager,login_user,logout_user,
                             login_required,current_user)
from flask.ext.bcrypt import check_password_hash

import forms
import models


DEBUG=True
HOST='0.0.0.0'
PORT=8000

app=Flask(__name__)
app.secret_key='fartbox99'

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"""
    g.db=models.DATABASE
    g.db.connect()
    g.user=current_user

@app.after_request
def after_request(response):
    """Close the database"""
    g.db.close()
    return response

@app.route('/register', methods=['GET','POST'])
def register():
    form=forms.RegisterForm()
    if form.validate_on_submit():
        flash("You Successfully registered", "success")
        models.User.create_user(
            email=form.email.data,
            password=form.password.data
        )
        return redirect(url_for('index'))
    return render_template('register.html', form=form)

@app.route('/')
def index():
    try:
        tacos=models.Taco.select()
    except models.DoesNotExist:    
        return render_template('índex.html')
    else:
        return render_template('index.html', tacos=tacos)

@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 does not 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("email or password doesn't match!", 'error')
    return render_template('login.html', form=form)

@app.route('/logout')
@login_required
def logout():
    flash("You've been logged out.", 'success')
    return redirect(url_for('index'))

@app.route('/taco', methods=['POST'])
@login_required
def taco():
    form=forms.TacoForm()
    if form.validate_on_submit:
        flash("You Successfully Created Your Taco", "success")
        models.Taco.create_taco(
        protein=form.protein.data,
        shell=form.shell.data,
        cheese=form.cheese.data,
        extras=form.extras.data,
        user=g.user._get_current_object()
        )
        return redirect(url_for('index'))
    return render_template('taco.html', form=form)

if __name__ == '__main__':
    models.initialize()
    try:
        models.User.create_user(
            email="chrisgraz@gmail.com",
            password='reallycomplicatedpassword'
        )
    except ValueError:
        pass
    #app.run(debug=DEBUG, host=HOST, port=PORT)
models.py
import datetime

from flask.ext.bcrypt import Bcrypt, generate_password_hash, check_password_hash
from flask.ext.login import UserMixin
from peewee import *


DATABASE=SqliteDatabase('social.db')

class User(UserMixin, Model):
    email=CharField(unique=True)
    password=CharField(max_length=100)

    class meta:
        database=DATABASE

    @classmethod    
    def create_user(cls, email, password):
        try:
            with DATABASE.transaction():
                cls.create(
                email=email,
                password=generate_password_hash(password))
        except IntegrityError:
            raise ValueError('User already exists')

class Taco(Model):
    protein=CharField()
    shell=CharField()
    cheese=BooleanField(default=False)
    extras=CharField()
    user=ForeignKeyField(rel_model=User, related_name='tacos')

    class meta:
        database=DATABASE

    @classmethod
    def create_taco(cls, protein, shell, cheese, extras, user):
        with DATABASE.transaction():#this is something I had in my notes
            cls.create(
                protein=protein,
                shell=shell,
                cheese=cheese,
                extras=extras,
                user=user)

def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Taco],safe=True)
    DATABASE.close()
forms.py
from flask_wtf import Form
from wtforms import StringField, PasswordField, TextField, BooleanField
from wtforms.validators import (DataRequired, Email, Length,
                                EqualTo, Regexp, ValidationError)

from models import User

def email_exists(form, field):
    if User.select().where(User.email==field.data).exists():
        raise ValidationError('User with that email already exists.')

class RegisterForm(Form):
    email=StringField(
        'Émail',
        validators=[
            DataRequired(),
            Email(),
            email_exists
        ])
    password=PasswordField(
        'Password',
        validators=[
            DataRequired(),
            Length(min=8),
            EqualTo('password2',message='Passwords must match!')            
        ])
    password2=PasswordField(
        'Confirm Password',
        validators=[
            DataRequired()
        ])


class LoginForm(Form):
    email=StringField(
        'Émail',
        validators=[
            DataRequired(),
            Email()
        ])
    password=PasswordField(
        'Password',
        validators=[
            DataRequired()            
        ])

class TacoForm(Form):
    protein=StringField('Protein',validators=[DataRequired()])
    shell=StringField('Shell',validators=[DataRequired()])
    cheese=BooleanField('Cheese')
    extras=TextField('Extras')  
templates/layout.html
<!doctype html>
<html>
  <head>
    <title>Tacocat</title>
    <link rel="stylesheet" href="/static/css/normalize.css">
    <link rel="stylesheet" href="/static/css/skeleton.css">
    <link rel="stylesheet" href="/static/css/tacocat.css">
  </head>
  <body>
    {% with messages=get_flashed_messages() %}
        {% if messages %}
            <div class="messages">
              {% for message in messages %}
              <div class="message">
                {{ message }}
              </div>
              {% endfor %}
            </div>
        {% endif %}
    {% endwith %}

    <div class="container">
      <div class="row">
        <div class="u-full-width">
          <nav class="menu">
          <!-- menu goes here -->
          {% if current_user.is_authenticated() %}
            <a href="{{ url_for('logout') }}">Log Out</a>
            <a href="{{ url_for('taco') }}">Add A New Taco</a>  
          {% else %}
            <a href="{{ url_for('login') }}">Log In</a>
            <a href="{{ url_for('register') }}">Sign Up</a>
          {% endif %}
          </nav>
          {% block content %}{% endblock %}
        </div>
      </div>
      <footer>
        <p>An MVP web app made with Flask on <a href="http://teamtreehouse.com">Treehouse</a>.</p>
      </footer>
    </div>
  </body>
</html>
templates/index.html
{% extends 'layout.html' %}

{% block content %}
<h2>Tacos</h2>
    {% if tacos.count() %}
        <table class="u-full-width">
          <thead>
            <tr>
              <th>Protein</th>
              <th>Cheese?</th>
              <th>Shell</th>
              <th>Extras</th>
            </tr>
          </thead>
          <tbody>
        {% for taco in tacos %}
            <tr>
              <!-- taco attributes here -->
              <th>{{taco.protein}}</th>
              <th>{{taco.cheese}}</th>
              <th>{{taco.shell}}</th>
              <th>{{taco.extras}}</th>
            </tr>
        {% endfor %}
          </tbody>
        </table>
    {% else %}
        <!-- message for missing tacos -->
        <h2>No Tacos Yet</h2>
    {% endif %}
{% endblock %}

2 Answers

Chris Grazioli
Chris Grazioli
31,225 Points

Kenneth Love Thanks for taking a look so quick man.

Thats weird, It ran and passed. (what happened?)

BUT Also: I ran tacocat.py to start the server and look at the page online, and I get a peewee.OperationalError: table taco has no column named user_id when I try to add a taco from the "/taco" endpoint

Whats the heck is up with that?

Chris Grazioli
Chris Grazioli
31,225 Points

Kenneth Love when I run app_test.py the test stops briefly, says:

treehouse:~/workspace$ python app_tests.py
../usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/wtforms/fields/core.py:350: DeprecationWarning: The TextField alias for StringField has been deprecated and will be removed in WT Forms 3.0
return self.field_class(*self.args, **kw)

.........

Ran 11 tests in 13.426s

OK

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Your code passes in my code challenge editor (where I make the CCs) but I had to change one thing about how it was run. Try your code again and see if it passes?