I
I
Ivan Voronin2020-06-04 08:45:19
SQLite
Ivan Voronin, 2020-06-04 08:45:19

What is the error when passing an object to the database?

When sending data from the form, it gives an error, I study the flask for one day, so I absolutely do not understand what the problem is and I ask you not to bully me much.

from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    intro = db.Column(db.String(300), nullable=False)
    text = db.Column(db.Text, nullable=False)
    day = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return '<Article %r>' % self.id


db.create_all()
db.session.commit()


@app.route('/')
@app.route('/home')
def index():
    return render_template("index.html")


@app.route('/create_article', methods=['POST', 'GET'])
def create_article():
    if request.method == "POST":
        title = request.form['title']
        intro = request.form['intro']
        text = request.form['text']

        article = Article(title=title, intro=intro, text=text)

        try:
            db.session.add(article)
            db.session.commit()
            return redirect('/create_article')
        except Exception:
            return 'Error'
    else:
        return render_template("create_article.html")


if __name__ == "__main__":
    app.run(debug=True)


'create_article.html' -
<div class="container"
    <h1>Добавление статьи</h1>
    <form method="post">
        <input type="text" name="title" id="title" class="form-control"><br>
        <textarea name="intro" id="intro" class="form-control"></textarea><br>
        <textarea name="text" id="text" class="form-control"></textarea><br>
        <input type="submit" class="btn btn-success" value="Отправить">
    </form>
</div>

Mistake -
5ed968e8a1f43606789134.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2020-06-06
@skipirich

Looks like your tables are not created.
before the first route add
db.create_all()
db.session.commit( ) Like
this

db.create_all()
db.session.commit()

@app.route('/')
@app.route('/home')

Yes, and such an exception handler except Exception: - bad practice

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question