sqliteflask-sqlalchemycrud

SQLAlchemy not updating db due AttributeError


I have a "edit task" page on a crm project with flask and I have built a POST route to update the db and then redirect to "tasks page". However, I keep receiving the AttributeError for: 'NoneType' object has no attribute 'tarefa'. However, I have declared 'tarefa' on db, it being a text of what should the task be, passed by the user:

class Tarefas(db.Model):
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    cliente_id: Mapped[int] = mapped_column(Integer, nullable=False)
    tarefa: Mapped[str] = mapped_column(String(250))
    tipo: Mapped[str] = mapped_column(String(250))
    prioridade: Mapped[str] = mapped_column(String(250))
    prazo: Mapped[Date] = mapped_column(Date)
    status: Mapped[str] = mapped_column(String(250))
    observacao: Mapped[str] = mapped_column(String(500), nullable=True)
    mesa: Mapped[int] = mapped_column(Integer)

here is my backend:

@app.route('/editar_tarefa/<int:id>', methods=["POST", "GET"])
@login_required
def editar_tarefa(id):
    if request.method == "POST":
        tarefa = request.form.get('tarefa')
        prioridade = request.form.get('prioridade')
        prazo = request.form.get('prazo')
        prazo = datetime.strptime(prazo, "%Y-%m-%d").date() if prazo else None
        status = request.form.get('status')
        observacao = request.form.get('observacao')
        mesa = request.form.get('mesa')
        if mesa == 'mesa':
            mesa = 1
        else:
            mesa = 0
        with app.app_context():
            tarefa_to_update = db.session.execute(db.select(Tarefas).where(Tarefas.id == id)).scalar()
            print(tarefa_to_update.tarefa )
            tarefa_to_update.tarefa = tarefa
            tarefa_to_update.prioridade = prioridade
            tarefa_to_update.prazo = prazo
            tarefa_to_update.status = status
            tarefa_to_update.observacao = observacao
            tarefa_to_update.mesa = mesa
            db.session.commit()
        return redirect(url_for("tarefas"))
    user_name = session.get('user_name')
    result = db.session.execute(db.select(Tarefas).where(Tarefas.id == id))
    tarefa = result.scalar()
    return render_template("editar_tarefa.html", tarefa=tarefa, user_name=user_name)

I have added "with app.app_context():" when I faced the problem the first time but it didn't solved. I have also verified my db with DB Browser for SQLite software and the names are as declared.

how can I solve it?


Solution

  • The problem is the object tarefa_to_update is None.

    This return None:

    db.session.execute(db.select(Tarefas).where(Tarefas.id == id)).scalar()
    

    you should use:

    tarefa_to_update = db.session.execute(db.select(Tarefas).where(Tarefas.id == id)).scalar()
    if tarefa_to_update is None:
        # return a 404 or raise exception