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

My code isn't working; It seems to be fine... (Register route in Flask)

When I go to /register I get an error that says "UnboundLocalError: local variable 'form' referenced before assignment". However, it points to where I AM assigning it.

Can somebody explain and help out please? Thank you :)

register route:

@app.route('/register', methods=('GET', 'POST'))
def register():
    form = form.RegisterForm()  # The error is pointing to *this* line of code
    if form.validate_on_submit():
        flash("Yay! You successfully 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)

Snapshot of Workspace

Thanks! ~Alex

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Can you provide the full stack trace of the error?

What do you mean?

The error I'm providing is the full error.

Here's app.py:

app.py
from flask import (Flask, g, render_template, flash, redirect, url_for)
from flask.ext.login import LoginManager

import forms
import models

DEBUG = True
PORT = 8000
HOST = '0.0.0.0'

app = Flask(__name__)
app.secret_key = 'sdfjgksur9sfgjsfgsfg;sldfgjs;rt095eutisfgihdsfghjdfhlasdfrg'

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 = form.RegisterForm()
    if form.validate_on_submit():
        flash("Yay! You successfully 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='xela888',
            email='alexdavison888@gmail.com',
            password='password'
        )
    except ValueError:
        pass
    app.run(debug=DEBUG, host=HOST, port=PORT)

Also, you can check my snapshot if you'd like.

Sorry, I didn’t get here in time :)

It's Ok hum4n01d :)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

These don't agree:

import forms

# Doesn't match 

def register():
    form = form.RegisterForm() # <-- should be "forms.RegisterForm()"

Thank you so much!!! :_)