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

Trying to create a new post, but getting "AttributeError: '_AppCtxGlobals' object has no attribute 'user'"

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

(social) D:\code\web-projects\social-network>python app.py
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 121-751-838
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [21/Aug/2017 20:50:43] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:50:43] "GET /static/css/normalize.min.css HTTP/1.1" 304 -
127.0.0.1 - - [21/Aug/2017 20:50:43] "GET /static/css/main.css HTTP/1.1" 304 -
127.0.0.1 - - [21/Aug/2017 20:50:43] "GET /static/js/vendor/disTime.min.js HTTP/1.1" 304 -
127.0.0.1 - - [21/Aug/2017 20:50:43] "GET /static/js/main.js HTTP/1.1" 304 -
127.0.0.1 - - [21/Aug/2017 20:50:44] "GET /static/img/icon-power.svg HTTP/1.1" 304 -
127.0.0.1 - - [21/Aug/2017 20:50:44] "GET /static/img/icon-logo.svg HTTP/1.1" 304 -
127.0.0.1 - - [21/Aug/2017 20:50:44] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [21/Aug/2017 20:50:48] "GET /logout HTTP/1.1" 302 -
127.0.0.1 - - [21/Aug/2017 20:50:48] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:50:48] "GET /static/img/icon-profile.svg HTTP/1.1" 304 -
127.0.0.1 - - [21/Aug/2017 20:50:52] "GET /register HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:50:58] "GET /login HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:51:00] "POST /login HTTP/1.1" 302 -
127.0.0.1 - - [21/Aug/2017 20:51:00] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:51:02] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [21/Aug/2017 20:52:40] "GET /new_post HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:53:05] "POST /new_post HTTP/1.1" 500 -
Traceback (most recent call last):
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask_login\utils.py", line 228, in decorated_view
    return func(*args, **kwargs)
  File "D:\code\web-projects\social-network\app.py", line 105, in post
    models.Post.create(user=g.user._get_current_object(),
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
AttributeError: '_AppCtxGlobals' object has no attribute 'user'
127.0.0.1 - - [21/Aug/2017 20:53:05] "GET /new_post?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:53:05] "GET /new_post?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:53:05] "GET /new_post?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:53:05] "GET /new_post?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 20:53:05] "GET /new_post?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 21:21:20] "POST /new_post HTTP/1.1" 500 -
Traceback (most recent call last):
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\flask_login\utils.py", line 228, in decorated_view
    return func(*args, **kwargs)
  File "D:\code\web-projects\social-network\app.py", line 105, in post
    models.Post.create(user=g.user._get_current_object(),
  File "C:\Users\Mlamba\Envs\social\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
AttributeError: '_AppCtxGlobals' object has no attribute 'user'
127.0.0.1 - - [21/Aug/2017 21:21:20] "GET /new_post?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 21:21:20] "GET /new_post?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 21:21:20] "GET /new_post?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 21:21:21] "GET /new_post?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2017 21:21:21] "GET /new_post?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
from flask import Flask, g, render_template, flash, redirect, url_for
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 = 5000
HOST = '0.0.0.0'

app = Flask(__name__)
app.secret_key = b'Xd\x05]\xed[\xb5 \xdc\x88;\xd8 !I\xc7\xb5\x99\xaf?\xd5\xb0\x16\xd7'

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'


@login_manager.user_loader
def load_user(userid):
    try:
        # look up a models.User instance with the id and return it
        return models.User.get(models.User.id == userid)
    except models.DoesNotExist:
        # Return None if the User doesn't exist
        return None


@app.before_first_request
def before_request():
    """
    Connect to the database before each request i.e open a connection when a request is started
    set g.db to the DATABASE variable in models and call the .connect() method
    """
    # g.db = models.DATABASE
    # g.db.connect()
    models.DATABASE.connect()
    g.user = current_user


@app.after_request
def after_request(response):
    """ Close the database connection after each request i.e close a connection when the response is delivered"""
    # g.db.close()
    models.DATABASE.close()
    return response


@app.route('/register', methods=['GET', 'POST'])
def register():
    # create an instance of the RegistrationForm from forms
    form = forms.RegistrationForm()
    if form.validate_on_submit():
        flash("You have successfully registered", "success")
        # use the models.User.create_user() method to create a new User from the form data
        models.User.create_user(
            username=form.username.data,
            email=form.email.data,
            password=form.password.data
        )
        return redirect(url_for('index'))
    # render and return the register.html template
    # In the template's context, name the RegistrationForm instance as form
    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 and validate the user.
                # user should be an instance of your `User` class
                login_user(user)
                flash("You've successfully 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():
    logout_user()
    flash("You've successfully logged out", "success")
    return redirect(url_for('index'))


@app.route('/new_post', methods=['GET', 'POST'])
@login_required
def post():
    """ instantiate, process, and send PostForm to the template.
        If the form is valid after submission, create a new post object with the data
        and set the user to the current user.
    """
    form = forms.PostForm()
    if form.validate_on_submit():
        models.Post.create(user=g.user._get_current_object(),
                           content=form.content.data.strip())
        flash("Message posted! Thanks!", "success")
        return redirect(url_for("index"))
    return render_template('post.html', form=form)


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


@app.route('/stream')
@app.route('/stream/<username>')
def stream(username=None):
    template = 'stream.html'
    if username and username != current_user.username:
        user = models.User.select().where(models.User.username**username).get()
        stream = user.posts.limit(100)
    else:
        stream = current_user.get_stream().limit(100)
        user = current_user
    if username:
        template = 'user_stream.html'
    return render_template(template, stream=stream, user=user)


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