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!

Binyamin Friedman
Binyamin Friedman
14,615 Points

Bummer: Create a User through /registration

I keep getting this useless error: Bummer: Create a User through /registration

My code passes all the tests in the workspace.

tacocat.py
from flask import Flask, flash, g, redirect, render_template, url_for, session
from flask_bcrypt import check_password_hash
from flask_login import current_user, LoginManager, login_required, login_user, logout_user

import forms
import models

DEBUG = True
PORT = 8080
HOST = '0.0.0.0'

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

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('/')
def index():
    tacos = models.Taco.select()
    return render_template('index.html', tacos=tacos)


@app.route('/registration', methods=['GET', 'POST'])
def register():
    form = forms.RegisterForm()
    if form.validate_on_submit():
        try:
            models.User.create_user(
                email=form.email.data,
                password=form.password.data
            )
        except ValueError:
            flash("Email taken", 'error')
        else:
            flash("Registered " + form.email.data, 'success')
            return redirect(url_for('index'))
    return render_template('register.html', form=form)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if g.user.is_authenticated():
        return redirect(url_for('index'))
    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)
                session['user_id'] = user.id
                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('/logout')
def logout():
    logout_user()
    flash("You've been logged out", 'success')
    return redirect(url_for('index'))


@app.route('/taco', methods=['GET', 'POST'])
@login_required
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,
        )
        return redirect(url_for('index'))
    return render_template('taco.html', form=form)


if __name__ == '__main__':
    models.initialize()
    #app.run(debug=DEBUG, host=HOST, port=PORT)
models.py
from flask_bcrypt import generate_password_hash
from flask_login import UserMixin
from peewee import *

DATABASE = SqliteDatabase('tacocat.db')


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

    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):
    user = ForeignKeyField(User, related_name='tacos')
    protein = CharField()
    shell = CharField()
    cheese = BooleanField()
    extras = TextField()

    class Meta:
        database = DATABASE


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, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Email, EqualTo, Length, ValidationError

import models


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


class RegisterForm(Form):
    email = StringField("Email", validators=[
            DataRequired(),
            Email(),
            email_available
        ])
    password = PasswordField("Password", validators=[
            DataRequired(),
            Length(min=4, max=50),
            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", validators=[DataRequired()], default="None")
    shell = StringField("Shell", validators=[DataRequired()])
    cheese = BooleanField("Cheese?", validators=[DataRequired()])
    extras = TextAreaField("More details", validators=[Length(max=150)])
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?abc=1">
    </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="header">
                <div class="grid-33">
                    <a href="{{ url_for('index') }}" class="icon-logo"></a>
                </div>
                <div class="grid-33">  
                    <p class="centered">Hello{% if current_user.is_authenticated() %} {{ current_user.email }}{% endif%}</p>
                </div>
                <div class="grid-33 right">
                    {% if current_user.is_authenticated() %}
                        <div class="grid-50">
                            <a href="{{ url_for('taco') }}" class="right" title="Taco">Add a new taco</a>
                        </div>
                        <div class="grid-50">
                           &nbsp;| <a href="{{ url_for('logout') }}" title="Log out">Logout</a>
                        </div>
                    {% else %}
                        <div class="grid-50">
                            <a href="{{ url_for('login') }}" class="right" title="Log in">Login</a>
                        </div>
                        <div class="grid-50">
                           &nbsp;| <a href="{{ url_for('register') }}" title="Register">Sign up</a>
                        </div>
                    {% endif %}
                </div>
                <br>
            </div>
            <br>
            {% block content %}{% endblock %}
            <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>
            <th>{{ taco.protein }}</th>
            <th>{{ taco.cheese }}</th>
            <th>{{ taco.shell }}</th>
            <th>{{ taco.extras }}</th>
        </tr>
    {% endfor %}
      </tbody>
    </table>
{% else %}
    <p>No tacos yet!</p>
{% endif %}
{% endblock %}