I query data from my "data.sqlite"'s database, run my project and get "sqlite3.OperationalError: no such table: blog_post". It would be great if you could help me fix this error. Thank you!
I created a table called "BlogPost", its table name as "blog_post" in the models.py:
class BlogPost(db.Model):
__tablename__ = 'blog_post'
users = db.relationship(User)
blog_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer,db.ForeignKey('users.id'), nullable=False)
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) #
problem_name = db.Column(db.String(140), nullable=False)
text = db.Column(db.Text, nullable=False)
blog_image = db.Column(db.String(140), nullable=False, server_default='default_blog.jpg')
def __init__(self, text, problem_name, user_id, blog_image):
self.text = text
self.problem_name = problem_name
self.user_id = user_id
self.blog_image = blog_image
def __repr__(self):
return f"Post ID: {self.post_id} -- Date:{self.date}---{self.problem_name}"
Using query console, I checked and see that this table is storing data just fine and I can see that there is no error.
I wanted to query data from this table and show it to the HTML file on my web page so I imported it with the command "myproject.models import BlogPost" into the python file called "views.py" (My Pycharm IDE show that the command is working fine and show no error)
Then I have these codes below:
from flask import render_template, request, Blueprint
import _sqlite3
...some other import
init_db()
conn = _sqlite3.connect('data.sqlite', check_same_thread=False)
c = conn.cursor()
core = Blueprint('core', __name__)
@core.route('/', methods=['GET', 'POST'])
def index():
search = Blogsearch_form(request.form)
if request.method == 'POST':
c.execute("SELECT * FROM blog_post WHERE problem_name LIKE (?)", ('%' + str(search) + '%',))
results = c.fetchall()
return render_template('blog_search_result.html', results=results)
Picture of my data.sqlite database:
I query to see the table blog_post in the console and it identified that the table name is blog_post. It also shows all the data I inputted in the website:
By the way, this is one of the code that I used to create my "data.sqlite" database inside my project's init.py:
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,
'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False