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 Takin' Names Macros

the validators message doesn't show

when I tried hitting the Register button after filling the username field like the viedo does, the message "Username should be one word, letters,numbers, and underscores only." doesn't show on the screen, but when I finished filling all the field and pressed register button, those messages showed up, anyone knows why? I have checked all the questions about validation that were asked below this "Macros" course , and I also checked the code line by line, still have no idea what's wrong

app.py

from flask import (Flask, g, render_template, flash, redirect, url_for)
from flask_login import LoginManager

import forms
import models

DEBUG = True
PORT = 8000
HOST = '127.0.0.1'

app = Flask(__name__)
app.secret_key = "dfskjdfhjk3.4340sokfldskl;sker;wk;ritipe2934u3o5990jskjfkwej!"

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()


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


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


@app.route('/')
def index():
    return 'Hey'


if __name__ == '__main__':
    models.initialize()
    try:
        models.User.create_user(
            username="kennethlove",
            email="kenneth@teamtreehouse.com",
            password="password",
            admin=True
        )
    except ValueError:
        pass
    app.run(debug=DEBUG, host=HOST, port=PORT)

models.py

import datetime

from flask_bcrypt import generate_password_hash
from flask_login import UserMixin
from peewee import *


DATABASE = SqliteDatabase("social.db")


class User(UserMixin, Model):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField(max_length=100)
    joined_at = DateTimeField(default=datetime.datetime.now)
    is_admin = BooleanField(default=False)

    class Meta:
        database = DATABASE
        order_by = ('-joined_at',)

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


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

forms.py

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

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 RegisterForm(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()]
    )

register.html

{% from 'macros.html' import render_field %}

<form method="POST" action="" class="form">
    {{ form.hidden_tag() }}
    {% for field in form %}
        {{ render_field(field) }}
    {% endfor %}
    <button type="submit" id="submit">Register</button>
</form>

macros.html

{% macro render_field(field) %}
    <div class="field">
        {% if field.errors %}
            {% for error in field.errors %}
                <div class="notification error">{{ error }}</div>
            {% endfor %}
        {% endif %}
        {{ field(placeholder=field.label.text) }}
    </div>
{% endmacro %}

@Megan Amendola Hi Megan! I have updated the post, thanks!

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Michael Nock! I'd be interested to know if you're doing this locally and if you've run pip install email-validator. It might be helpful to get this code as either a GitHub repository (with a requirements.txt) file or a workspace snapshot so that we can assist more quickly.

Hi Jennifer Nordell , thanks for your reply! Yes I did this on locally, on pycharm, I think I´ve run the pip install email-validator, I checked that in terminal, it said ¨Requirement already satisfied....¨

here is the workspace snapshot: https://w.trhou.se/ngzyzocwoa

Thank you so much!