A
A
AliminVerckon2021-02-22 21:00:49
Flask
AliminVerckon, 2021-02-22 21:00:49

Why is saving to the database not working?

Model

class Docs(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name_doc = db.Column(db.String, index=True, nullable=True)
    files = db.Column(db.String, index=True, nullable=True)
    format_id = db.Column(db.Integer, db.ForeignKey('format.id'))

Sample
<h1>Добавление документов</h1>
    <form enctype="multipart/form-data" action="", method="post">
        <div class="row">
            <div class="col-lg-5">
                <h4>Имя</h4>
                <input class="form-control form-control-lg" type="text", name="name_doc" id="name_doc">
            </div>
            <div class="col-lg-5">
                <h4>Файл</h4>
                <input class="form-control form-control-lg" type="file", name="file" id="file">
            </div>
            <div class="col-lg-2">
                <h4>Формат</h4>
                <input class="form-control form-control-lg" type="number" name="format_id" id="format_id">
            </div>
        </div>
        <input class="form-control form-control-lg" type="submit" name="submit" id="submit">
    </form>
    <div class="container good">
        {% with messages = get_flashed_messages() %}
            {% if messages %}
                <ul class=flashes>
                    {% for message in messages %}
                        <li>{{ message }}</li>
                    {% endfor %}
                </ul>
            {% endif %}
        {% endwith %}
    </div>

Add Code
@app.route(
'/docs_add', methods=['POST', "GET"])
def DAdd():
    global path
    forms = AddDocsForm()
    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            if forms.validate_on_submit():
                do = Docs(name_doc=forms.name_doc.data(), files=path, format_id=forms.format_id.data())
                db.session.add(do)
                db.session.commit()
                flash("Success: Записано")
                return redirect('/')
            else:
                flash("Error: Не удалось записать данные")

    return render_template('/DAdd.html', title="Добавление документов", key=keyurl)

the form
class AddDocsForm(FlaskForm):
    name_doc = StringField('Name', validators=[DataRequired()])
    format_id = IntegerField('Format id', validators=[DataRequired()])
    submit = SubmitField('Submit')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gleb, 2021-02-24
@AliminVerckon

Add SQLALCHEMY_ECHO = True in the config and see what the ORM sends to the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question