E
E
EnotShow2021-11-11 20:14:51
Flask
EnotShow, 2021-11-11 20:14:51

How to add something to BD, get something from BD?

The code:

spoiler

from flask import Flask, request, flash
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.testing import db
from wtforms_alchemy import ModelForm

app = Flask(__name__)
app.config.update(
    DEBUG=True,
    Secret_key='This must been secret !',

    SQLALCHEMY_DATABASE_URI='sqlite:///app_db.db',
    SQLALCHEMY_TRACK_MODIFICATIONS=False,

    WTF_CSRF_ENABLE=False,
)

db = SQLAlchemy(app)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, index=True)
    post_name = db.Column(db.String(75), nullable=False)
    post_body = db.Column(db.String(3000), nullable=False)


class Comments(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, index=True)

    post_id = db.Column(
        db.Integer,
        db.ForeignKey('post.id'),
        index=True,
        nullable=False,
    )

    post = db.relationship('Post', foreign_keys=[post_id, ])

    post_comment = db.Column(db.String(1500), nullable=False)

    def __str__(self):
        return '<Comments %r>' % self.data


class PostForm(ModelForm):
    class Meta:
        model = Post()


# Some wrong here !!!!!!!!!!!!!!!!!!
@app.route('/')
def index():
    return Post.querry.all()


# And here !!!!!!!!!!!!!!!!!!!!!
@app.route('/add_post', methods=['POST'])
def add_post():
    form = PostForm(request.form)
    if form.validate():
        post = Post(**form.data)
        db.session.add(post)
        db.session.commit()
        return ('Post added !', 200)
    else:
        return ('Bad input', 200)


if __name__ == '__main__':
    db.create_all()

    app.run()


1. How to add something to the database in this case? When I execute a post, an exception appears leading to the internal logic of flask?
Post request:
618d4d58a6d49649081669.png
2. To get something from the database you need to use Post.querry.all()., but it doesn't work
.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaratPetrov96, 2021-11-12
@MaratPetrov96

Not Post.query.all(), but Post.query.all().
You should immediately master the templating and display this data on a simple page.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question