flask - NameError: global name 'User' is not defined -
i follow miguelgrinberg tutorial , want make profile page without login page when have http:.../user/peg said got error,i think because couldn't connect database. put data in user python command
>>> u = models.user(nickname='peg', email='peg@email.com') >>> db.session.add(u) >>> db.session.commit()
i have question database store user , post? , why didn't define table?( because in app.db have table 3 column 1.reponsity_id 2. reponsity_path 3. id) , please tell me how can solve error. thanx
views.py
from app import app flask import render_template, flash, redirect @app.route('/') @app.route('/index') def index(): user = {'nickname': 'miguel'} posts = [ { 'author': {'nickname': 'john'}, 'body': 'beautiful day in portland!' }, { 'author': {'nickname': 'susan'}, 'body': 'the avengers movie cool!' } ] return render_template("index.html", title='home', user=user, posts=posts) @app.route('/user/<nickname>') def user(nickname): #here got error nameerror: global name 'user' not defined user = user.query.filter_by( nickname = nickname).first() posts = [ {'author': user, 'body': 'test post #1'}, {'author': user, 'body': 'test post #2'} ] return render_template('user.html', user=user, posts=posts)
models.py
from app import db class user(db.model): id = db.column(db.integer, primary_key=true) nickname = db.column(db.string(64), index=true, unique=true) email = db.column(db.string(120), index=true, unique=true) posts = db.relationship('post', backref='author', lazy='dynamic') def __repr__(self): return '<user %r>' % (self.nickname) class post(db.model): id = db.column(db.integer, primary_key = true) body = db.column(db.string(140)) timestamp = db.column(db.datetime) user_id = db.column(db.integer, db.foreignkey('user.id')) def __repr__(self): return '<post %r>' % (self.body)
db_create.py
#!flask/bin/python migrate.versioning import api config import sqlalchemy_database_uri config import sqlalchemy_migrate_repo app import db import os.path db.create_all() if not os.path.exists(sqlalchemy_migrate_repo): api.create(sqlalchemy_migrate_repo, 'database repository') api.version_control(sqlalchemy_database_uri, sqlalchemy_migrate_repo) else: api.version_control(sqlalchemy_database_uri, sqlalchemy_migrate_repo, api.version(sqlalchemy_migrate_repo))
user.html
<!-- extend base layout --> {% extends "base.html" %} {% block content %} <h1>user: {{ user.nickname }}!</h1> <hr> {% post in posts %} <p> {{ post.author.nickname }} says: <b>{{ post.body }}</b> </p> {% endfor %} {% endblock %}
you need import models views
module:
from models import user
Comments
Post a Comment