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 The Challenge

Nthulane Makgato
Nthulane Makgato
Courses Plus Student 19,602 Points

Failing a few tests. Please help

This is a great challenge. Had it not been there, I would have passed this course without actually knowing the work. Flask has been quite challenging for me.

Coded my version of the solution but I am failing 5 of the tests and I need some guidance. I have gone through the flask lessons again just to make sure. I understand the work much better but I don't understand what my code is missing to pass this test.

I am failing the following tests: test_empty_db test_logged_in_menu test_logged_out_menu test_taco_create test_registration


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

DEBUG = True
PORT = 8000
HOST = ''

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

login_manager = LoginManager()
login_manager.login_view = 'login'

def load_user(userid):
      return models.User.get(models.User.id == userid)
  except models.DoesNotExist:
      return None

def before_request():
  """Connect to the database before each request."""
  g.db = models.DATABASE
  g.user = current_user

def after_request(response):
  """Close the database connection after each request."""
  return response

@app.route('/register', methods=('GET', 'POST'))
def register():
  form = forms.RegisterForm()
  if form.validate_on_submit():
      flash("Yay, you registered!", "success")
          email = form.email.data,
          password = form.password.data
      return redirect(url_for('index'))
  return render_template('register.html', form=form)

@app.route('/login', methods=('GET', 'POST'))
def login():
  form = forms.LoginForm()
  if form.validate_on_submit():
        user = models.User.get(models.User.email == form.email.data)
    except models.DoesNotExist:
        flash("Email is incompatible", "error")
        if check_password_hash(user.password, form.password.data):
            flash("You are logged in", "success")
            return redirect(url_for('index'))
            flash("Password does not match", "error")
  return render_template('login.html', form=form)

def logout():
    flash("You've been logged out! Come back soon!", "success")
    return redirect(url_for('index'))

@app.route('/new_taco', methods=('GET','POST'))
def taco():
    form = forms.TacoForm()
    if form.validate_on_submit():
        models.Taco.create(user = g.user._get_current_object(),
                           protein = form.protein.data,
                           shell = form.shell.data,
                           cheese = form.cheese.data,
                           extras = form.extras.data.strip()
        flash("Your taco has been added!!", "success")
        return redirect(url_for('index'))
    return render_template('taco.html', form=form)

def index():
  tacos = models.Taco.select().limit(10)
  return render_template('index.html', tacos=tacos)

if __name__== '__main__':
    with models.DATABASE.transaction():
          email = 'billy@example.com',
          password = 'password'
  except ValueError:
  app.run(debug=DEBUG, host=HOST, port=PORT)


import datetime

from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *

DATABASE = SqliteDatabase('taco.db')

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

    class Meta:
      database = DATABASE

    def get_tacos(self):
      return Taco.select().where(Taco.user == self)

    def get_stream(self):
      return Taco.select().where(
          (Taco.user == self)

    def create_user(cls, email, password):
          email = email,
          password = generate_password_hash(password))
      except IntegrityError:
        raise ValueError("User already exists")

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

    class Meta:
      database = DATABASE

def initialize():
  DATABASE.create_tables([User, Taco], safe=True)


from flask_wtf import Form
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import (DataRequired, ValidationError, Email,
                               Length, EqualTo)

from models import User

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

class RegisterForm(Form):
    email = StringField(
        validators = [
    password2 = PasswordField(
        'Confirm Password',
        validators = [DataRequired()]
    password = PasswordField(
            EqualTo(password2, message='Passwords must match')

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

class TacoForm(Form):
    protein = StringField('Protein')
    shell = StringField('Shell', validators = [DataRequired()])
    cheese = BooleanField('Cheese')
    extras = TextAreaField("Any extras?")


{% extends 'layout.html' %}

{% block content %}
    {% if tacos.count() %}
        <table class="u-full-width">
        {% for taco in tacos %}
              <!-- taco attributes here -->
              <td>{{ taco.protein }}</td>
              <td>{{ taco.cheese }}</td>
              <td>{{ taco.shell }}</td>
              <td>{{ taco.extras }}</td>
        {% endfor %}
    {% else %}
        <!-- message for missing tacos -->
        <div class="messages">There aren't any tacos</div>

    {% endif %}
{% endblock %}


<!doctype html>
    <link rel="stylesheet" href="/static/css/normalize.css">
    <link rel="stylesheet" href="/static/css/skeleton.css">
    <link rel="stylesheet" href="/static/css/tacocat.css">
    {% with messages=get_flashed_messages() %}
    {% if messages %}
        <div class="messages">
          {% for message in messages %}
          <div class="message">
            {{ message }}
          {% endfor %}
    {% endif %}
    {% endwith %}

    <div class="container">
      <div class="row">
        <div class="u-full-width">
          <nav class="menu">
            <!-- menu goes here -->
            {% block content %}
              {% if current_user.is_authenticated %}
                  <a href="{{ url_for('logout') }}" title="Log out">Logout</a>
              {% else %}
                  <a href="{{ url_for('login') }}" title = "Log in">Login</a>
                  <a href="{{ url_for('register') }}" title="Register">Register</a>
              {% endif %}

            {% endblock %}

        <p>An MVP web app made with Flask on <a href="http://teamtreehouse.com">Treehouse</a>.</p>

I hope that this is everything I know that this is quite a problem to unravel. I would appreciate any assistance. Thank you!!