0

I have a working web app built with flask and MySQL database with SQLAlchemy.

As part of further development, I have created a new table in the database, called 'buggies'. Previous tables in the database such as post were set up before the web was turned into a package, and I can still add and delete posts to this table.

However, the new table, called 'buggies' doesn't seem to be displaying the table contents on the home page - home.html.

Error log (excerpt):

Error running WSGI application
2020-04-17 08:29:28,946: jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got ':'
2020-04-17 08:29:28,946:   File "/usr/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
2020-04-17 08:29:28,946:     return self.wsgi_app(environ, start_response)

I also do not seem to be able to connect to the database through SQLAlchemy, python3 in bash:

>>> from flask_app import db
>>> Post.query.all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Post' is not defined
>>> from flask_app.models import db
>>> Post.query.all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Post' is not defined

>>> from flask_app import db                                                                                                                                
>>> Buggies.query.all()                                                                                                                                     
Traceback (most recent call last):                                                                                                                          
  File "<stdin>", line 1, in <module>                                                                                                                       
NameError: name 'Buggies' is not defined                                                                                                                    
>>> from flask_app.models import db
>>> Buggies.query.all()                                                                                                                                     
Traceback (most recent call last):                                                                                                                          
  File "<stdin>", line 1, in <module>                                                                                                                       
NameError: name 'Buggies' is not defined                                                                                                                    
>>>  

MySQL:

mysql> show tables;
+----------------------+
| Tables_in_olbliss$CF |
+----------------------+
| buggies              |
| post                 |
| user                 |
+----------------------+
3 rows in set (0.01 sec)

mysql> describe buggies;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| BName        | varchar(100) | NO   |     | NULL    |                |
| BRider       | varchar(100) | YES  |     | NULL    |                |
| lastmodified | datetime     | YES  |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

mysql> select * from buggies;
+----+------------------+--------+---------------------+
| id | BName            | BRider | lastmodified        |
+----+------------------+--------+---------------------+
|  1 | Kawasaki         | Bob    | 2020-04-17 07:53:29 |
|  2 | Stewarding Buggy |        | 2020-04-17 07:55:50 |
|  3 | Parking Buggy    |        | 2020-04-17 07:56:10 |
+----+------------------+--------+---------------------+
3 rows in set (0.01 sec)

mysql> 

init.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager

app = Flask(__name__)
app.config["DEBUG"] = True

app.config['SECRET_KEY'] = '...'

SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username="xxxxx",
    password="xxxxx",
    hostname="xxxxx",
    databasename="xxxxx",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db  = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'

from flask_app import routes

routes.py

@app.route('/')
@app.route('/h')
@app.route('/home')
def home():
    posts = Post.query.all()
    buggies = Buggies.query.all()
    return render_template('home.html', posts=posts, buggies=buggies)

home.html (there isn't anything in layout.html which would cause a problem)

{% extends "layout.html" %}
{% block content %}
<p>{% for buggy in buggies %}
            {{ buggy:BName }}
        {% endfor %}</p>
{% endblock content %}

models.py

class Buggies(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    BName = db.Column(db.String(100), nullable=False)
    BRider = db.Column(db.String(100), nullable=True)
    lastmodified = db.Column(db.DateTime, nullable=True, default=datetime.utcnow)

    def __repr__(self):
        return f"Buggies('{self.BName}', '{self.BRider}','{self.lastmodified}')"

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    description = db.Column(db.Text, nullable=False)
    status = db.Column(db.String(100), nullable=False)
    assigned_to = db.Column(db.String(100), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"Post('{self.title}', '{self.date_posted}')"

forms.py

class BuggyForm(FlaskForm):
    BName = StringField('Name of Buggy', validators=[DataRequired()])
    BRider = StringField('Name of Rider')
    lastmodified  = DateTimeField('Date and Time', format='%Y-%m-%d %H:%M:%S')
    submit = SubmitField('Save')
6
  • there seems to be a jinja2 exception. can you show your html file Commented Apr 17, 2020 at 9:08
  • Thanks, it's given above, below the routes and above models. Thank you. Commented Apr 17, 2020 at 9:13
  • when you call buggies = Buggies.query.all() can you get all the elements in the list Commented Apr 17, 2020 at 9:15
  • check my answer Commented Apr 17, 2020 at 9:20
  • when I run Bggies.query.all() in python3 in bash, it says 'Buggies' is not defined. (it seems to be a connection issue to the databse, though, in other routes not shown in this question, I can successfully create and delete buggy rows in the web app into and out of the mysql database) Commented Apr 17, 2020 at 9:21

1 Answer 1

1

To check the list use this code

for buggy in buggies:
    print(buggy.BName)

Also try changing your html to this:

<p>{% for buggy in buggies %}
            {{ buggy['BName'] }}
        {% endfor %}</p>
Sign up to request clarification or add additional context in comments.

1 Comment

Changing the html file seems to have worked, I'll keep tesring it! Why would changing to ['BName'] work - out of interest? Also, adding the top code to init.py just crashes the site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.