Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Build a Social Network with Flask Tacocat Challenge Tacocat!

Not Quite Sure what's going wrong

Keep getting "Bummer! Try Again!" Anyone mind reading through my code to see what the issue may be? Perhaps there's something i'm missing?

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

DEBUG = True
PORT = 8000
Host = '0.0.0.0'

app = Flask(__name__)
app.secret_key = 'gaa094863qol*&^*&^*&%)'

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():
    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.RegistrationForm()
    if form.validate_on_submit():
        models.User.create_user(
            username = form.username.data,
            email = form.email.data,
            password = form.password.data)
        return redirect(url_form('index'))
    return render_template('register.html', form = form)

@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 render_template('login.html', form = form)

@app.route('/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)
        flash("You have created a new taco, congrats!", "success")
        return dedirect(url_for('index'))
    return render_template('taco.html', form = form)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/')
def index():
    tacocats = models.Taco.select().limit(50)
    return render_template('index.html', tacocats = tacocats)


if __name__ == '__main__':
    models.initialize()
    try:
        models.User.create_user(
            username = "Taco the Cat",
            email = "taco.felinefine@whiskerswhiskey.com",
            password = "trololol"
    )
    except ValueError:
        pass
    #app.run(debug = DEBUG, host = HOST, port = PORT)
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):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField(max_length=100)


    class Meta:
        database = database

    @classmethod
    def create_user(cls, username, email, password):
        try:
            cls.create(
                username = username,
                email = email,
                password = generate_password_hash(password)
            )
        except IntegrityError:
            raise ValueError("User already exists")

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

    class Meta:
        database = database

def initialize():
    database.connect()
    database.create_tables([User, Taco], safe = True)
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):
    if User.select().where(User.username == field.data).exists():
        raise ValidationError("User with that name already exists.")

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

class RegistrationForm(Form):
    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(
        "Confirm password",
        validators = [DataRequired()]
    )

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

class TacoForm(Form):
    protein = StringField("Protein")
    shell = StringField("Shell")
    cheese = BooleanField("With Cheese")
    extras = TextAreaField("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">
            {% 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>
               <td>{{ taco.protein }}</td>
               <td>{% if taco.cheese %} Yes {% else %} No {% endif %} </td>
               <td>{{ taco.shell }}</td>
               <td>{{ taco.extras }}</td>
            </tr>
        {% endfor %}
          </tbody>
        </table>
    {% else %}
        You have no Tacos currently
    {% endif %}
{% endblock %}

1 Answer

double check in layout.html, it looks like in your url_for expressions there's an issue with quote marks. Be sure to use different quote marks inside your phrase like "{{url_for('taco')}}"