Hey All: As of version SQLAlchemy 3.0 to create your db file you will need to run some commands like this in the shell : from project import app, db app.app_context().push() db.create_all() Then the .db file is created in a folder called "Instance" in your project. Hope this helps some one
I was able to get the database created, but none of the follow-up steps worked for me. I'm sure given enough time I could find a fix, but I'm short on it, so I'm hoping it works well enough for rest of the tutorial.
@@MattFussell Everything else works as in the video. But I don't really like that the database is stored in the Instance directory. I changed the path to the database file as described in Miguel Grinberg's book. import os basedir = os.path.abspath(os.path.dirname(__file__)) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'site.db') Maybe it will be useful for others.
I somehow managed to create this site.db but now , 1- I couldn't able to run any other command for entering the users in command prompt (getting same out of context error) 2 - if adding the user within our with app.app_context(): db.create_all() user 1= details..... db.session.add(user1) By doins so I am still getting a integrity error for email , even its unique
@@harshitpathak5958 My DB knowledge is thin, so apply the appropriate amount of salt. It sounds like you may have an error in your ORM code - like the field has been set to expect one thing and receiving something else.
For anyone who is facing the error of 'outside application context', try this : - in your terminal: from import app, db - with app.app_context(): db.create_all() Note: You can use this also when you will want to add data to the database. GoodLuck!
Well - while this gets me beyond the immediate 'application context' error, it takes me off the path shown in Corey's video. I am planning on abandoning this series in favor of a more up to date offering. Thank you for your insight.
In my university I'm attending a course of Information System in which the professor is using exactly your code in the labs lessons without mentioning you. I found you by looking for help on youtube.
@@X............................. Your display picture made me scratch my monitor screen! Felt like a fool when I realized it was just your picture. This is pure evil genius!
@@matthewbotti That is a pretty naive view of things. I have learned lots from youtube and google in general but i still would not trade in my college education. There are things college cant teach you or give real world experience in but it does set you up well for "learning how to learn" and developing your career. It helps create the foundation that you will build upon for the rest of your career. Just learning from youtube will teach you some things but it doesn't quite give you the solid foundation that college will or as good an understanding. I studied electronic engineering (which includes programming) and I read some hobbyist forums sometimes where people have learned stuff themselves but they also lack some pretty important knowledge and understanding. It usually takes the handful of talented guys on those forums to bring up the level of everyone else who still have to ask simple questions or to correct some opinions that are not accurate etc. Same for places like stack overflow. people asking basic questions because they learned something online but they hit one bump on the road and don't have the background/understanding to figure it out themselves and have to go ask online and wait for someone else to solve it for them. And for the record, in Europe we pay far less for college education than say the USA. €1500 a year is what i paid and had no debt after it.
One of the clearest, most understandable and easy to follow instructional videos on the topic. Much much better than 99.9% (OK, I could have written 100%....) of what I have seen around.
Ive been playing with laravel for several months, but after seeing how clean and simple flask is, I'm probably going to jump onto python. Thank you for this amazing reference
If db.create_all() is not creating the file for you, check that you wrote URI and not URL in "app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'". Don't be me xD Following this tutorial in WLS2 but in my Windows 10's VS Code accessing Ubuntu remotely. Working perfectly so far. To set up VS Code of Windows 10 to work with your Ubuntu WLS, following this: code.visualstudio.com/remote-tutorials/wsl/getting-started Amazing tutorial so far!
Note: When using Postgres as Production DB, SQLAlchemy creates a table name 'user' from Class User. 'user' is a reserved table in postgres and is used for db admin users. Using pgAdmin I could not see that my table existed. My db worked but I couldn't see the table in pgAdmin sidebar. I could only see the reserved 'user' table. I had to use SELECT * FROM "user"; (double quotes) to get my data. I changed Class 'User' to 'Users' to avoid later confusion. Not sure if this is similar behavior in other dbs. Hope it saves someone a day of head scratching!
@@irishRocker1 it's free knowledge. his presentation is in depth and easy to follow. you paid for a free service because you didn't want to wait 5 whole seconds.
Hi Corey! First off, I want to say thank you for all of these comprehensive tutorials that you shared with us! I really appreciate all the work that you've done on your channel! With regards to my concern, I was wondering what steps I should take when converting from an SQLite database to a PostgreSQL one. Hope you could enlighten me on this one. Thank you again very much!
23:44 "user = User.query.get(1)" while running this query ... :1: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) The warning you're seeing is indicating that the Query.get() method is considered legacy in SQLAlchemy and will be deprecated in version 2.0. Instead, it suggests using the Session.get() method. solution- "user = db.session.get(User, 1)"
Exceptional video. Your examples are on point and flow very well. I find you explanations clear and very concise. They explain everything I need to know with out rambling. Any questions that came to my mind were answered in the video. (Get out of my mind you freaking mind reader! Ha ha) All technical videos should take a note from how this was made. Well done, and thank you. I'm sure a lot of hard work and forethought went into this.
Thanks for this great video. Tried to code along with the similar tutorial from Flask itself but that one is difficult to understand. Here you break it up in nice pieces and use much more intuitive coding. Thank you very much....
Omg, thanks for sharing that with us! It threw "sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize" and answers on the web were very confusing, this one did the job!
for anyone whose having an issue with db.create_all(), use the following commands after watching the next video. (env) C:.\..\..\flask app\Flask_blog>set FLASK_APP=run (env) C:.\..\..\flask app\Flask_blog>flask shell >>> from flaskblog import db >>> from flaskblog.models import User, Post >>>db.create_all()
Really like the quality of these videos. Great tutorial. Took some time to wrap my head around the datetime.utcnow part and why it should be without the (), especially after creating post1 in the terminal and the datetime was Null. But after running the .add(post1) and the .commit() it all made sense.
@@sonny8595 if u do datetime.utcnow() then the function will get executed and will return a DateTime and that returned value will be assigned as default we dont want that we want get current datetime everytime
Great series Corey, I'm recommending your channel to everyone I meet! To anyone getting an error: sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects.sqllite when running $ db.create_all() - I solved this by pip installing an earlier version of SQLAlchemy (1.2.7) [my previous version was 1.2.16] and this solved the problem. Thought it might help someone.
One very basic question..related to the python about this lecture...why we mostly use class attributes in python while accessing DB? Example why we didnt use self.username or self.id , etc here and used. Example: class User(db.Model): id=db.Column(db.Integer, primary_key=True) username=db.Column(db.String(20), unique=True, nullable=False) email=db.Column(db.String(120), unique=True, nullable=False)
I'm getting this error, when I try to run db.create_all() in terminal: RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed the current application. To solve this, set up an application context with app.app_context(). See the documentation for more information.
@handari5549 Why didn't Corey have to do this? Is it because of a difference in versions? Edit. seems like I needed to add db.init_app(app) after the line db=SQLAlchemy()
Love this series (and have watched several of your others, including the learning python series). Thanks! Wish you would have discussed indexes and when and how you use them. Thanks again!
If you use the filter_by function with say username='Corey' and you had users with usernames Corey and say CoreyS, would it pick up both of them or only the exact match Corey? Thanks for a great video!
filter_by() is going to return an exact match. If there are more than one username='Corey', User.query.filter_by(username='Corey').all() would return all of them. On the other hand, if you wanted all of the variants, you could use something like User.query.filter(User.username.like == '%Corey%')).all(). This would return a list of all the username that contained the string 'Corey'. Love the question --- you made my look up the answer!
i got the same problem as you so this is what I did, hopefully, it will work for you 1.pip install pylint-flask 2Load the installed plugin. For example, if you use VS code, please edit setting.json file as follows: (opened with the File > Preferences > Settings command ⌘, search for settings.json and one of the options will let you edit it) add this line "python.linting.pylintArgs": ["--load-plugins", "pylint_flask"]
Hello, I just wanna add some remarks. I had the same problem, but for me the solution was to install the pylint_flask_sqlalchemy additionally to the pylint_flask plugin. This post (pypi.org/project/pylint-flask-sqlalchemy/) shows all the steps including the load of the plugin through the command line. For someone that uses VSCode, it is worth pointing that one should add the following lines to the .pylintrc file: load-plugins=pylint_flask,pylint_flask_sqlalchemy Hope that this can be useful for somebody!
Best flask tutorial i have seen. helped me start my own projects. I Have a question however, if you can show how to do many to many relationship that would be helpfull.
I am getting an error when I try to db.create_all(). The error is: "RuntimeError: Working outside of application context". This even happens when I try to run the source code. Any idea why?
thanks this is an awesome tutorial. good to follow, good explaination. and the biggest point is the free source code to look back at. for reference if i am walking to an unexpected error. so thanks a lott. you helping me a lot with this tutorial
Wonderful tutorial, thanks alot! Everything went fine until 19:55. when typing in the user_1=... in the terminal I get following error: "sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|User|user'. Original exception was: Could not determine join condition between parent/child tables on relationship User.posts - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression." Also when typing in db.create_all() following error occurs: "sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'post.user_id' could not find table 'user_id' with which to generate a foreign key to target column 'None'" I have copied the code straight from Corey github just to be sure... Any idea as to why this is happening?
flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/ - this helped me out. make a quests user and then create the user_1 - mine worked all of a sudden.
1 year after lol but yeah I got this too, fixed it when I put my Posts class above my User class. Also the second thing about can’t find user_id table, the foreign key is “user.id” not “user_id”
There appears to be a recent update to werkzeug that prevents the command from flaskblog import db from working (th-cam.com/video/cYWiDiIUxQc/w-d-xo.htmlm46s). pip install werkzeug==0.16.0 seems to fix it. see github.com/scoringengine/scoringengine/issues/670
Yes! Thank you for the solution this is exactly what I was searching for. Is this a problem from the first pip installs not covering this, or was something changed in an update?
For those who have an error like "has no 'Column' member" or "'db is not defined", just add in settings.json this line and save: "python.linting.pylintArgs": ["--load-plugins", "pylint-flask"] I am running it on VS code on a mac.
Error : sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|User|user'. Original exception was: When initializing mapper Mapper|User|user, expression 'Post' failed to locate a name ("name 'Post' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined. All that I did different was to change blogpost.py to app.py Can You Please Help ?
It is probably too late, but I ran into the same error. I had a couple of spelling errors. However as you edit you will get the same errors over and over again. You may have also entered the python commands in wrong into the terminal. Best option is create a new instance of the terminal. Then re enter all the commands. THis worked for me. from flaskblog import db db.create_all() from flaskblog import User, Post user_1 = User(username='Test', email='t@t.com', password='p') db.session.add(user_1)
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: user.email [SQL: 'INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)'] [parameters: ('Corey', 'C@demo.com', 'default.jpg', 'password')] (Background on this error at: sqlalche.me/e/gkpj)
Hello, can anyone help me with this error? : Traceback (most recent call last): File "C:/Users/lucia/PycharmProjects/Flask_blog/flaskblog.py", line 13, in class User(db.Model): File "C:/Users/lucia/PycharmProjects/Flask_blog/flaskblog.py", line 14, in User id = db.Column(db.Integer, primary_key=True) TypeError: Column() got an unexpected keyword argument 'primary_key' Process finished with exit code 1 Thank you !
for those who have sqlalchemy has no column member error while working on vs code please do some changes in settings preference>settings>edit>setting.json>copy and paste the below code { "python.linting.pylintArgs": [ "--load-plugins", "pylint-flask" ] }
I might have been the only one confused by this. But if you create a post object in memory, and haven't done the "db.session.commit()" yet, you will see "None" for the id and the datetime, because the database does that work. It's obvious to me now, but if anyone is confused why they are getting "None" for any of the values, just make sure you've committed your changes first.
Hey All: As of version SQLAlchemy 3.0 to create your db file you will need to run some commands like this in the shell :
from project import app, db
app.app_context().push()
db.create_all()
Then the .db file is created in a folder called "Instance" in your project.
Hope this helps some one
Thank you very much. It really helps me.
I was able to get the database created, but none of the follow-up steps worked for me. I'm sure given enough time I could find a fix, but I'm short on it, so I'm hoping it works well enough for rest of the tutorial.
@@MattFussell Everything else works as in the video. But I don't really like that the database is stored in the Instance directory. I changed the path to the database file as described in Miguel Grinberg's book.
import os
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'site.db')
Maybe it will be useful for others.
I somehow managed to create this site.db but now , 1- I couldn't able to run any other command for entering the users in command prompt (getting same out of context error)
2 - if adding the user within our
with app.app_context():
db.create_all()
user 1= details.....
db.session.add(user1)
By doins so I am still getting a integrity error for email , even its unique
@@harshitpathak5958 My DB knowledge is thin, so apply the appropriate amount of salt. It sounds like you may have an error in your ORM code - like the field has been set to expect one thing and receiving something else.
For anyone who is facing the error of 'outside application context', try this :
- in your terminal: from import app, db
- with app.app_context():
db.create_all()
Note: You can use this also when you will want to add data to the database. GoodLuck!
Oh wow! You saved me! I have been stuck for days with this error and was ready to throw out the entire tutorial.
I owe you a beer! Thanks VERY MUCH!
Well - while this gets me beyond the immediate 'application context' error, it takes me off the path shown in Corey's video.
I am planning on abandoning this series in favor of a more up to date offering.
Thank you for your insight.
@@mikevogt71 These bugs really blow one's mind lol but they should never be a roadblock, just keep trying, you will learn alot!
Thnks for killing the fustration
Thank you for posting this
Behind the smooth voice is tons of debugging and eternities of reading the docs
Most of which is trying to find the 1 damnable parenthesis or quotes
Corey Schafer is teaching us things which we did not learn in universities. I promise I will support you through Patreon once I land a job.
Thanks! Glad you found the videos helpful!
Me too!
I will too
Did you land a job yet?
my uni is teaching me this
17:04 made me so happy when you noticed that and fixed it. I had a solid 10 minutes of anxiety.
yeah, I was waiting for him to realize it, though I did it right in the first place ;)
lol
Hey Corey, you literally helped me Land a dream job . Thank you for all you've contributed.
In my university I'm attending a course of Information System in which the professor is using exactly your code in the labs lessons without mentioning you. I found you by looking for help on youtube.
Hey GT, do yo mind me asking which uni do you study at and which course? Thanks.
@@X............................. Your display picture made me scratch my monitor screen! Felt like a fool when I realized it was just your picture. This is pure evil genius!
University of Queensland?
If I am right you study at Università degli Studi di Napoli Federico II jajaja. Also love the number of likes in your comment!
@@matthewbotti That is a pretty naive view of things. I have learned lots from youtube and google in general but i still would not trade in my college education. There are things college cant teach you or give real world experience in but it does set you up well for "learning how to learn" and developing your career. It helps create the foundation that you will build upon for the rest of your career. Just learning from youtube will teach you some things but it doesn't quite give you the solid foundation that college will or as good an understanding. I studied electronic engineering (which includes programming) and I read some hobbyist forums sometimes where people have learned stuff themselves but they also lack some pretty important knowledge and understanding. It usually takes the handful of talented guys on those forums to bring up the level of everyone else who still have to ask simple questions or to correct some opinions that are not accurate etc. Same for places like stack overflow. people asking basic questions because they learned something online but they hit one bump on the road and don't have the background/understanding to figure it out themselves and have to go ask online and wait for someone else to solve it for them. And for the record, in Europe we pay far less for college education than say the USA. €1500 a year is what i paid and had no debt after it.
Your videos are really great! Every second of this video is understandable, that really takes talent! Keep it up!
Im completely agree. Great Videos.
As someone who wrote PHP 20 years ago, damn do I wish this existed then haha This is awesome. Thanks for your incredibly clear and concise videos
One of the clearest, most understandable and easy to follow instructional videos on the topic. Much much better than 99.9% (OK, I could have written 100%....) of what I have seen around.
Ive been playing with laravel for several months, but after seeing how clean and simple flask is, I'm probably going to jump onto python. Thank you for this amazing reference
While True:
Print("Thank You So Much")
Do keep in mind that Python is case sensitive!
Traceback (most recent call last):
File "", line 1, in
NameError: name 'Print' is not defined
Riddhiman 36 I'm pretty sure While isn't a keyword and this will fail on the first line
@@BurgerBurglar8964 'while' is a valid keyword.
Should read:
while True:
print("Thank You So Much")
God we're pedantic aren't we!
I think auto-correction is the culprit to blame here hhh
Dude, I am loving this series of videos, but MAN that was a challenging 29:57 minutes! Thank you thank you thank you for making this video
I watch at 2x speed.
@@irishRocker1 No one asked
If db.create_all() is not creating the file for you, check that you wrote URI and not URL in "app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'".
Don't be me xD
Following this tutorial in WLS2 but in my Windows 10's VS Code accessing Ubuntu remotely. Working perfectly so far.
To set up VS Code of Windows 10 to work with your Ubuntu WLS, following this: code.visualstudio.com/remote-tutorials/wsl/getting-started
Amazing tutorial so far!
When I'm no longer a broke college student I'll be joining your Patreon!!
Thanks!
Note: When using Postgres as Production DB, SQLAlchemy creates a table name 'user' from Class User. 'user' is a reserved table in postgres and is used for db admin users. Using pgAdmin I could not see that my table existed. My db worked but I couldn't see the table in pgAdmin sidebar. I could only see the reserved 'user' table. I had to use SELECT * FROM "user"; (double quotes) to get my data. I changed Class 'User' to 'Users' to avoid later confusion. Not sure if this is similar behavior in other dbs. Hope it saves someone a day of head scratching!
the best flask tutorial series hands down. i don't even mind the ads and i've had monstrous urges to break screens over them.
ah, reading comments like these makes me glad i subscribed for youtube premium lol adverts used to wreck my head!
@@irishRocker1 it's free knowledge. his presentation is in depth and easy to follow. you paid for a free service because you didn't want to wait 5 whole seconds.
This may be the best crash course on sqlalchemy. Love the series.
From watching your videos and reading these comments, I no longer regret not studying a computer science degree at university :)
Many thanks from Russia. Your educational videos are great.
You are the best teacher ever I had. many thanks to you, I can now connect the dots and, understand how do these libraries work together. Respect.
bro. genius , love the way you teach.
on vacation actually, pumped to learn here at a cafe in the middle of patagonia. keep it up
Whoa, that sounds like an awesome vacation!
Couldn't find a better teacher and programmer> Amazing teaching techniques. Thank You Corey
Hi Corey! First off, I want to say thank you for all of these comprehensive tutorials that you shared with us! I really appreciate all the work that you've done on your channel!
With regards to my concern, I was wondering what steps I should take when converting from an SQLite database to a PostgreSQL one. Hope you could enlighten me on this one. Thank you again very much!
this is the most detailed tutorial i have ever seen
i'm watching every video in this tutorial
Have been doing coding since 15 years, but this is one of the best videos have seen so far. Respect!
It is the best video than my udemy courses I learn a lot form your video Thanks a lot sir continue your series..
This is my first time with database and it is really simple because of you thanks again
23:44 "user = User.query.get(1)" while running this query ...
:1: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0)
The warning you're seeing is indicating that the Query.get() method is considered legacy in SQLAlchemy and will be deprecated in version 2.0. Instead, it suggests using the Session.get() method.
solution-
"user = db.session.get(User, 1)"
by the way Corey you are the best tutor ever on youtube
Exceptional video. Your examples are on point and flow very well. I find you explanations clear and very concise. They explain everything I need to know with out rambling. Any questions that came to my mind were answered in the video. (Get out of my mind you freaking mind reader! Ha ha) All technical videos should take a note from how this was made. Well done, and thank you. I'm sure a lot of hard work and forethought went into this.
Wow, you are starting super fast in this video, I first though my video is set on 1.25 speed :). Thanks a lot for your tutorials by the way!
Good teacher... Your teaching style is amazing. Each and every line is clearer and to the point..
OMG, this is one of the best tutorials that I have found on YT. I'll see what I can to help.
Thanks for this great video. Tried to code along with the similar tutorial from Flask itself but that one is difficult to understand. Here you break it up in nice pieces and use much more intuitive coding. Thank you very much....
If you are getting error while creating new user, you can try to change lazy="True" to lazy="dynamic"
I had to spend 2 hours, before i figure it out.
Omg, thanks for sharing that with us! It threw "sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize" and answers on the web were very confusing, this one did the job!
@@lipcioful man you saved me .You wasted 2hours but i waste 4hours solving this one. Thanks!
I changed lazy="True" to lazy="dynamic" still I am getting this error
Thanks for the tweak
@@r.h.5172 save the work and in the python shell import the tables again `from flaskblog import User, Post` before creating the user.
for anyone whose having an issue with db.create_all(), use the following commands after watching the next video.
(env) C:.\..\..\flask app\Flask_blog>set FLASK_APP=run
(env) C:.\..\..\flask app\Flask_blog>flask shell
>>> from flaskblog import db
>>> from flaskblog.models import User, Post
>>>db.create_all()
Really like the quality of these videos. Great tutorial.
Took some time to wrap my head around the datetime.utcnow part and why it should be without the (), especially after creating post1 in the terminal and the datetime was Null. But after running the .add(post1) and the .commit() it all made sense.
Could you explain it to us?
@@sonny8595 if u do datetime.utcnow() then the function will get executed and will return a DateTime
and that returned value will be assigned as default
we dont want that
we want get current datetime everytime
Will you make a tutorial for switching SQLAlchemy database to production one?
Thanks!!
Thanks Corey! Really helpful as I'm trying to finish up my first web app in Flask.
Dude you are so talented and know how to commincate
Your videos are the best thank you so much
you are simple best and you provide high quality education for free ❤️❤️ thanks a lot 🙏
Thank you so much, your teaching is clear and easy to understand! It helps me a lot.
Amazing , superb and best video of flask python in whole internet , TH-cam and all
I love this guy's tutorial series.
The quality of the content is so good. It's so understandable and useful.
Hello Corey, please include a tutorial for making a Many-to-Many relationship in Flask-SQLAlchemy. Thanks
Thank you Corey. You cover all that is necessary within reasonable time yet in details.
Great series Corey, I'm recommending your channel to everyone I meet! To anyone getting an error:
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects.sqllite when running $ db.create_all() - I solved this by pip installing an earlier version of SQLAlchemy (1.2.7) [my previous version was 1.2.16] and this solved the problem. Thought it might help someone.
you did sqllite not sqlite in app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' (i did the same thing :-/)
Around 18:30, for those who are having module error or name error at terminal, please try to write python -m pip install flask_wtf or whatever.
thank you ! This saved me so much time !
if that doesn't work just use every different type of pip install e.g. python3-m pip install .... pip3 install ...... should work
thanks!!!
One very basic question..related to the python about this lecture...why we mostly use class attributes in python while accessing DB?
Example why we didnt use self.username or self.id , etc here and used.
Example:
class User(db.Model):
id=db.Column(db.Integer, primary_key=True)
username=db.Column(db.String(20), unique=True, nullable=False)
email=db.Column(db.String(120), unique=True, nullable=False)
If someone manages to mess up at 21:25 and now are getting an error do remember to close of the session before trying again using db.session.close().
Thank you for that. Idk what fixed my "SQLite objects created in a thread can only be used in that same thread." issue but this may have been it!
This video really helped me a lot, everything is clear now tysm Corey !
I'm getting this error, when I try to run db.create_all() in terminal:
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
i am stucked here from 2 days
You have to manually set the context-
>>> from project import app, db
>>> app.app_context().push()
>>> db.create_all()
@handari5549 Why didn't Corey have to do this? Is it because of a difference in versions?
Edit. seems like I needed to add
db.init_app(app)
after the line
db=SQLAlchemy()
This was by far the best tutorial on integrating sqlalchemy with python! thanks man!!
The command to install Flask-SQLAlchemy in the video is out of date now, please use below instead:
pip install -U Flask-SQLAlchemy
Both the commands work just fine.
@@keshavbansal5148 no, first command don't working more
@@PythonDevelopment if you follow the requirements file, you will find that it does work fine'
Thank you sooo much for the tutorials!! It helped me big time for my project. You teach way better than my teachers.
what project did you make ?....i'm a beginner and need to make a project ..can you please guide me a little?
To make that sqlalchemy warning disappear add this
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
Love this series (and have watched several of your others, including the learning python series). Thanks! Wish you would have discussed indexes and when and how you use them. Thanks again!
If you use the filter_by function with say username='Corey' and you had users with usernames Corey and say CoreyS, would it pick up both of them or only the exact match Corey? Thanks for a great video!
filter_by() is going to return an exact match. If there are more than one username='Corey', User.query.filter_by(username='Corey').all() would return all of them.
On the other hand, if you wanted all of the variants, you could use something like User.query.filter(User.username.like == '%Corey%')).all(). This would return a list of all the username that contained the string 'Corey'.
Love the question --- you made my look up the answer!
Thank you so much Corey , Your Videos have taught me a lot about python and Web development, You are amazing!
Hi there,
I encountered an error which says cannot import Flask from flask while importing db from flaskblog. Please help
This is a step above a lot of videos in terms of DB set up. Nice work!
hey there hows it going everybody
Hi @Corey! Thank for the series I had some headache until I found your videos to resolve my little issues :D Thanks !
i get errors with this line of code, db.Column(db.String(60), nullable=False)
it says " Instance of 'SQLAlchemy' has no 'Column' member"
i got the same problem as you so this is what I did, hopefully, it will work for you
1.pip install pylint-flask
2Load the installed plugin.
For example, if you use VS code, please edit setting.json file as follows: (opened with the File > Preferences > Settings command ⌘, search for settings.json and one of the options will let you edit it)
add this line
"python.linting.pylintArgs": ["--load-plugins", "pylint_flask"]
@@lieuich6184 Thank you very much!
Hello,
I just wanna add some remarks. I had the same problem, but for me the solution was to install the pylint_flask_sqlalchemy additionally to the pylint_flask plugin. This post (pypi.org/project/pylint-flask-sqlalchemy/) shows all the steps including the load of the plugin through the command line.
For someone that uses VSCode, it is worth pointing that one should add the following lines to the .pylintrc file:
load-plugins=pylint_flask,pylint_flask_sqlalchemy
Hope that this can be useful for somebody!
How to resolve this problem in Pycharm ??
@@lieuich6184 Hey this doesn't seem to help. Any other fixes?
Dude, your videos are so good! Very high quality and helpful. Thanks!
I keep coming back to Corey's videos for years. No one teaches like him. But he doesn't post new videos anymore. Sad!!
Best flask tutorial i have seen. helped me start my own projects. I Have a question however, if you can show how to do many to many relationship that would be helpfull.
I'm stuck on 17:30, I'm using Pycharm and I don't know how to create the database like you did. Please help.
@Squishy Chilli im also using pycharm and getting some error while using terminal
A universities never teach us these you are greate.
Sir its showing error when I am trying to import User, Post from flaskblog, saying : ImportError: cannot import name 'User' from 'flaskblog'
Check spelling of User or your main file name
In my opinion Peewee is more clear and understandable, but SQLA is nice too. Thanks for all of yours tuts
I am getting an error when I try to db.create_all(). The error is: "RuntimeError: Working outside of application context". This even happens when I try to run the source code. Any idea why?
i have been stuck on this for a while too did you figure it out?
@@weedwackerfannypacker Nope. Don't understand any of the explanations online. You?
'id' is coloured in orange. I think it's a keyword or method/function name. Great tutorial. SQLAlchemy is not so scary anymore. I will look at it.
You’re right. I should probably change that. Thanks for pointing that out!
I can't use db.Column, in the "class User(db.Model)" it says >>>>>>>> [pylint] E1101:Instance of 'SQLAlchemy' has no 'Column' member
HELP!!!!!!!!!!!
For me this worked : pip install pylint --upgrade
thanks this is an awesome tutorial. good to follow, good explaination. and the biggest point is the free source code to look back at. for reference if i am walking to an unexpected error. so thanks a lott. you helping me a lot with this tutorial
Hey, Corey
I got this error:
[pylint] E1101:Instance of 'SQLAlchemy' has no 'Column' member
How do I fix it?
Thank you.
Its an error within the python linter. If you are using VScode (like me) it shows an error in the editor but runs correctly
@@johnathaningle8855 I'm also running VSCode, and see the same error.
pip install flake8
@@johnathaningle8855 Disable Linter (pylint)
@@ElmerGLue Disable the Linter (pylint)
Thank you very much, your video helps me a lot.
Wonderful tutorial, thanks alot!
Everything went fine until 19:55. when typing in the user_1=... in the terminal I get following error:
"sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|User|user'. Original exception was: Could not determine join condition between parent/child tables on relationship User.posts - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression."
Also when typing in db.create_all() following error occurs:
"sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'post.user_id' could not find table 'user_id' with which to generate a foreign key to target column 'None'"
I have copied the code straight from Corey github just to be sure... Any idea as to why this is happening?
flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/ - this helped me out. make a quests user and then create the user_1 - mine worked all of a sudden.
1 year after lol but yeah I got this too, fixed it when I put my Posts class above my User class. Also the second thing about can’t find user_id table, the foreign key is “user.id” not “user_id”
Amazing tutorial. Everything is explained clearly and easy to follow.
There appears to be a recent update to werkzeug that prevents the command from flaskblog import db from working (th-cam.com/video/cYWiDiIUxQc/w-d-xo.htmlm46s).
pip install werkzeug==0.16.0 seems to fix it.
see github.com/scoringengine/scoringengine/issues/670
Yes! Thank you for the solution this is exactly what I was searching for. Is this a problem from the first pip installs not covering this, or was something changed in an update?
For those who have an error like "has no 'Column' member" or "'db is not defined", just add in settings.json this line and save:
"python.linting.pylintArgs": ["--load-plugins", "pylint-flask"]
I am running it on VS code on a mac.
Error :
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|User|user'. Original exception was: When initializing mapper Mapper|User|user, expression 'Post' failed to locate a name ("name 'Post' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined.
All that I did different was to change blogpost.py to app.py
Can You Please Help ?
i had the same problem. turned out i misspeling word 'ForeignKey'. after i corected it, i reopen project and it start working.
It is probably too late, but I ran into the same error. I had a couple of spelling errors. However as you edit you will get the same errors over and over again. You may have also entered the python commands in wrong into the terminal. Best option is create a new instance of the terminal. Then re enter all the commands. THis worked for me.
from flaskblog import db
db.create_all()
from flaskblog import User, Post
user_1 = User(username='Test', email='t@t.com', password='p')
db.session.add(user_1)
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: user.email [SQL: 'INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)'] [parameters: ('Corey', 'C@demo.com', 'default.jpg', 'password')] (Background on this error at: sqlalche.me/e/gkpj)
I also had this problem. it got me stuck a whole day
FOR THOSE...WHOSE SQLALCHEMY IS NOT WORKING....USE MOGODB AND PYTHON MODULE [FLASK-PYMONGO]
Thanks for this course videos, you're amazing at teaching
fun fact: you are in the comment section because db.create_all() didn't work
also fun fact: we care about the solution, not some lame joke
am i the only one who watches a 30min video in over an hour (coding included) ? :)
Hello, can anyone help me with this error? :
Traceback (most recent call last):
File "C:/Users/lucia/PycharmProjects/Flask_blog/flaskblog.py", line 13, in
class User(db.Model):
File "C:/Users/lucia/PycharmProjects/Flask_blog/flaskblog.py", line 14, in User
id = db.Column(db.Integer, primary_key=True)
TypeError: Column() got an unexpected keyword argument 'primary_key'
Process finished with exit code 1
Thank you !
Save your files, close your command prompt and restart it. It worked for me !
Sir you have sick teaching skills, omg .. I'll definetly become a patreon
Thank you, mr
Corey Schafer!
Simplemente excelente tutorial grascias Mister Corey
Excellent as always Corey. I would love to see a video about db migrations now. Thanks!
ur my mentor man , tq corey
I wish uni taught us all of this. Such a great course and instead I cam out of college only knowing theory lol
best Python Guru
for those who have sqlalchemy has no column member error while working on vs code
please do some changes in settings
preference>settings>edit>setting.json>copy and paste the below code
{
"python.linting.pylintArgs": [
"--load-plugins",
"pylint-flask"
]
}
It worked for me muthu, thanks a lot
thank you so so much for the videos! they were so helpful to navigate Python Flask :)
YOU DESERVE 1 MILLION SUBS!
Thank you so much these amazing explanations.
I might have been the only one confused by this. But if you create a post object in memory, and haven't done the "db.session.commit()" yet, you will see "None" for the id and the datetime, because the database does that work. It's obvious to me now, but if anyone is confused why they are getting "None" for any of the values, just make sure you've committed your changes first.