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!

BRIAN WEBER
BRIAN WEBER
21,570 Points

"Create a user through /registration" Tacocat Challenge

Can someone please tell me why I am receiving this error?

Thanks,

Brian

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

import forms
import models

DEBUG = True
PORT = 8000
HOST = '0.0.0.0'

app = Flask(__name__)
app.secret_key = 'dsaf4t478houajbv430t734youhf3134t7yg28$%#'

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


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


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


@app.route('/registration', methods=['GET', 'POST'])
def register():
    """Register new user here."""
    form = forms.RegisterForm()
    if form.validate_on_submit():
        flash("Yay, you've registered!", "success")
        models.User.create_user(
            email=form.email.data,
            password=form.password.data
        )
        return redirect(url_for('login'))
    return render_template('register.html', form=form)


@app.route('/login', methods=['GET', 'POST'])
def login():
    """Log in user."""
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.select().where(
                models.User.email == form.email.data).get()
        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('/logout')
@login_required
def logout():
    """Log out user."""
    logout_user()
    flash("You've been logged out!", "success")
    return redirect(url_for('index'))


@app.route('/taco', methods=['GET', 'POST'])
@login_required
def taco():
    """Create a taco."""
    form = forms.CreateTacoForm()
    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("Taco has been created!", "success")
        return redirect(url_for('index'))
    return render_template('taco.html', form=form)


if __name__ == '__main__':
    models.intialize()
    try:
        models.User.create_user(
          email="brianweber2@gmail.com",
          password="surfer17",
        )
    except ValueError:
        pass
models.py
from flask_login import UserMixin
from flask_bcrypt import generate_password_hash, check_password_hash
from peewee import *


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

    class Meta:
        database = DATABASE

    @classmethod
    def taco_creation(cls, user, protein, shell, cheese, extras):
        with DATABASE.transaction():
            cls.create(
                user=user,
                protein=protein,
                shell=shell,
                cheese=cheese,
                extras=extras
            )


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

from models import User


# Validator methods
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(
        'Email',
        validators=[
            DataRequired(),
            Email(),
            email_exists
    ])
    password = PasswordField(
        'Password',
        validators=[
            DataRequired(),
            Length(min=5),
            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 CreateTacoForm(Form):
    protein = StringField('Protein', validators=[DataRequired()])
    shell = StringField('Shell', validators=[DataRequired()])
    cheese = BooleanField('Cheese?', validators=[DataRequired()])
    extras = TextAreaField('Extras', validators=[DataRequired()])
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 not current_user.is_authenticated() %}
              <a href="{{ url_for('register') }}">Sign Up</a>
              <a href="{{ url_for('login') }}">Log In</a>
              {% else %}
              <a href="{{ url_for('taco') }}">Add a new taco</a>
              <a href="{{ url_for('logout') }}">Log Out</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 %}
            <!-- taco attributes here -->
        {% endfor %}
          </tbody>
        </table>
    {% else %}
        <!-- message for missing tacos -->
        <h3>No tacos yet!</h3>
    {% endif %}
{% endblock %}

What is the error you are receiving ?

BRIAN WEBER
BRIAN WEBER
21,570 Points

Hi Alex,

Below is the error I am getting.

failures [(<main.UserViewsTestCase testMethod=test_registration>, 'Traceback (most recent call last):\n File "", line 95, in test_registration\nAssertionError: 404 != 302\n')]

1 Answer

Ryan S
Ryan S
27,276 Points

Hi Brian,

One thing is that your app.route for the register view is '/registration' when it should be '/register' Although I'm guessing you changed it in an attempt to deal with the error (I did the same thing, it is a confusing error).

The second thing is that in your register view, you should return redirect(url_for('index')), instead of 'login'

I got your code to pass by changing only those two things. However, I noticed that in your index.html file you didn't display the taco attributes. Apparently the code can pass without them.

Good luck.

BRIAN WEBER
BRIAN WEBER
21,570 Points

Hi Ryan,

Thanks for the response!

I did change the app.route for the register view to '/register'. For some reason I was working on another project and set the redirect to the login page, but I have corrected it to be for the home page. My code also passed without displaying the taco attributes, which is strange. Maybe this is a bug that the Treehouse team can fix.

Brian