Python Forum
Having Trouble with Flask and SQLAlchemy
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Having Trouble with Flask and SQLAlchemy
#1
Just a little tid bit, I've been self teaching my self programming for about a year now (I'd say on average I code/learn 3 times a week, for about 2-3 hours.) All started from some random Ruby class that I took as an elective. At this point I've been learning Python and it's syntax by using Learn Python the Hard way, and now I've moved on to learning Flask with Michel Grenburg's tutorial. At some point during his tutorial I felt like "haha I have this" so I just started kind of doing things on my own. This was a mistake I believe. I've been having a load of trouble with working with databases. I have the html down, jinja templates make sense to me, but whenever I try to do something with any of the models I make either

1. Nothing that I expect to be shown is shown on my web page.

OR

2. I get a lot of weird errors telling me that certain tables don't exist.

It's been a real frustrating experience, and at this point I really can't tell what I'm doing wrong so I've joined this forum to hopefully get some advice. As of now, I've gotten around problem #2, but problem #1 is still giving me trouble. So can anyone tell me what I'm doing wrong here? (I've cut out things that I believe are irrelevant from my examples...)


Models.py

from app import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash

class Resource(db.Model): 
    id = db.Column(db.Integer,primary_key = True)
    type = db.Column(db.String(140), nullable = False, index = True ) 
    
    def __init__(self, type = None):
        self.type = type
    def __repr__(self):
        return '<Resource {}>'.format(self.type)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    resource_id = db.Column(db.Integer, db.ForeignKey('resource.id'),nullable=False) 
    resource_type = db.relationship('Resource', backref=db.backref('Post', lazy = True))
    title = db.Column(db.String(200), index = True, unique = True, nullable = False)
    description = db.Column(db.String(200), index = True, nullable = False) 
    body = db.Column(db.Text,index = True)
    timestamp = db.Column(db.DateTime, index = True, default = datetime.utcnow)
    author = db.Column(db.String(140), index = True)
    
    def __init__(self, title=None,description=None,body=None):
        self.title=title
        self.description=description
        self.body=body

    def __repr__(self):
        return 'Title:{}, Type:{}, Date Posted: {}'.format(self.title, self.posttype, self.timestamp) 
So those are my models. I managed to use the Flask.Admin module in order to create tests for each of them. Now here's my Routes, that are using the models.

Routes.py

 
@app.route('/resources/')
def resources():
    posts = Post.query.all()
    resources = Resource.query.all()
    
    return render_template('resources2.html')
And then finally, my actual template.

 
{% extends "base.html" %} 
{% block title %} Resources 2 {% endblock %} 
{% block app_content %} 

......

<section class = "articlesection">
<article> 
    
{% for post in posts %} 


<div class = "previews">
  <h3><a href="{{ url_for('{{ post.title }}') }}"> {{ post.title }} </a> </h3>
<hr> 
<br>
{{ post.description }}
{{ post.resource_type }} 
{{ post.timestamp }}
<br>
{{ post.author }}
    </div> 
{% endfor %}
    
    
{% for resource in resources %}
    
    {{ resource.type }}
{% endfor %}
    
    
    
    <p> FUUUCKOFKEDJAUSOIFDHJYUDSDSFDHFSOIFUDFSJFUDFOIJDFSOIJOFIJPOUOI (this is here basicaly to test if anythings working.....)</p>


</article> 
</section>

<section> 
<div class = "aside">
<ul>
<li><h4>Resources</h4></li>
<li>Articles</li>
<li>Fliers</li>
<li>Links</li>

</ul>

</div>

</section>
{% endblock app_content %} 
I would expect the above code to iterate through all of my Resources and Posts, and then post the attributes that I have specifically chosen. BUT NOTHING HAPPENS! I GET NOTHING! Here's a screenshot of the shown template!

[Image: w7o2Xf9]

If anyone at all can give my any advice I'd probably love you forever. I've been trying to make this website for a team of researchers for a while and I just feel like shit because I know doing wordpress would be easier but I wanted to learn Flask and now I've been stuck for like a month it feels like :(((( S.O.S
Reply
#2
I do'nt see the screenshot, also, you don't pass the posts and resources as parameters to render_template.

return render_template('resources2.html', posts=posts, resources=resources)
http://flask.pocoo.org/docs/1.0/quickstart/#rendering-templates
Reply
#3
Wow I'm really an idiot....Maybe I need to read the documentation more wowwwow. Thanks so much man, idk why the screenshot isn't working for you though, if you click the word image it should have taken you to an imgur page. Note to self, run database stuff as arguments to render_template. Okay.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Flask: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) database is locked pythonpaul32 1 2,029 Apr-04-2023, 07:44 AM
Last Post: Larz60+
  Flask error sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint pythonpaul32 2 3,494 Feb-21-2023, 03:13 AM
Last Post: noisefloor
  Flask and SQLAlchemy question: Database is being created but tables aren't adding pythonpaul32 3 4,415 Feb-07-2023, 10:48 AM
Last Post: pythonpaul32
  Error updating one to many relationship in Flask/ SQLAlchemy atindra 0 3,300 Apr-15-2021, 10:29 PM
Last Post: atindra
  Flask migrate sqlalchemy not found TomasAm 2 3,449 Dec-01-2020, 10:04 AM
Last Post: TomasAm
  python 3.7 on windows using flask and flask-sqlalchemy. Alpy 2 3,945 Aug-12-2020, 07:24 PM
Last Post: Alpy
  Flask-Sqlalchemy count products in specific category imawesome 2 25,655 Mar-12-2020, 08:14 PM
Last Post: imawesome
  Flask-SqlAlchemy - Relationship failed to locate a name - Please Help howardrwb 0 5,148 Jan-31-2020, 08:38 PM
Last Post: howardrwb
  flask-SQLAlchemy query with keyword as function argument pascale 2 3,450 Mar-13-2019, 08:45 PM
Last Post: Ecniv
  Flask - Implementing SQLAlchemy with Blueprints jolsendev 1 10,056 Nov-01-2018, 05:38 PM
Last Post: jolsendev

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020