我如何删除烧瓶中的 post

How do i delete a post in flask

我无法删除 Flask 中的个人 post。

@app.route('/delete/<int:id>',methods=['GET','POST'])
def delete(id):
    if request.method == 'GET':
        p=Blog.query.filter_by(id=id)
        db.session.delete(p)
        db.session.commit()
    return redirect(url_for('home'))

这是我的模板代码

{% extends "base.html" %} 
{% block content %} 

<body class="body">
    <div class="home">
        {% for blog in blog %} 
        <a class="link" href="#">Edit</a>
        <a href="{{url_for('delete',id=blog.id)}}">Delete</a>
        <h1>{{blog.title}}</h1>{{blog.posted_on}}
        <p>{{blog.post}}</p>
        {% endfor %}
    </div>
    </body>
{% endblock content %} 

这是错误

UnmappedInstanceError
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'flask_sqlalchemy.BaseQuery' is not mapped

Traceback (most recent call last)
File "/home/chirag/Desktop/develop/flaskprojects/myenv/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 2641, in delete
state = attributes.instance_state(instance)
The above exception was the direct cause of the following exception:
File "/home/chirag/Desktop/develop/flaskprojects/myenv/lib/python3.8/site-packages/flask/app.py", line 2095, in __call__
return self.wsgi_app(environ, start_response)
File "/home/chirag/Desktop/develop/flaskprojects/myenv/lib/python3.8/site-packages/flask/app.py", line 2080, in wsgi_app
response = self.handle_exception(e)
File "/home/chirag/Desktop/develop/flaskprojects/myenv/lib/python3.8/site-packages/flask/app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "/home/chirag/Desktop/develop/flaskprojects/myenv/lib/python3.8/site-packages/flask/app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/chirag/Desktop/develop/flaskprojects/myenv/lib/python3.8/site-packages/flask/app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "/home/chirag/Desktop/develop/flaskprojects/myenv/lib/python3.8/site-packages/flask/app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/home/chirag/Desktop/develop/flaskprojects/app.py", line 85, in delete
db.session.delete(p)
File "<string>", line 2, in delete
File "/home/chirag/Desktop/develop/flaskprojects/myenv/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 2643, in delete
util.raise_(
File "/home/chirag/Desktop/develop/flaskprojects/myenv/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'flask_sqlalchemy.BaseQuery' is not mapped
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
Brought to you by DON'T PANIC, your friendly Werkzeug powered traceback interpreter.

这是我的完整 app.py 代码

from email.policy import default
from enum import unique
from flask import Flask, render_template,redirect, request,url_for
from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from sqlalchemy import null
from wtforms import TextAreaField,SubmitField,StringField
from wtforms.validators import DataRequired
import os
from datetime import datetime
from flask_migrate import Migrate

app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True
db=SQLAlchemy(app)
migrate=Migrate(app,db)
SECRET_KEY=os.urandom(32)
app.config['SECRET_KEY']=SECRET_KEY


#database modules


class Blog(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    title=db.Column(db.String(30))
    post=db.Column(db.String(300))
    posted_on=db.Column(db.DateTime,default=datetime.utcnow)

#end of database modules

#Forms

class BlogForm(FlaskForm):
    title=StringField("title",validators=[DataRequired()])
    post=TextAreaField("Enter Your Post here",validators=[DataRequired()])
    submit=SubmitField("POST")

#end of form


#views

@app.route('/')
def home():
    title="Home"
    blog=Blog.query.all()
    kwargs={'title':title,
            'blog':blog}
    return render_template("home.html",**kwargs)


@app.route('/blog/',methods=['GET','POST'])
def create_blog():
    form=BlogForm()
    if form.validate_on_submit():
        new_post=Blog(title=form.title.data,post=form.post.data)
        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('home'))
    return render_template("blog.html",form=form)

@app.route('/blog<int:id>/')
def single_blog(id):
    blog=Blog.query.filter_by(id=id)
    title="Post"
    kwargs={'blog':blog,'title':title}
    return render_template("single_blog.html",**kwargs)

@app.route('/delete/<int:id>',methods=['GET','POST'])
def delete(id):
    if request.method == 'GET':
        p=Blog.query.filter_by(id=id)
        db.session.delete(p)
        db.session.commit()
    return redirect(url_for('home'))
   
#end of views

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

我不明白我收到的错误。我通过id查询了个人post,然后我删除了它,然后我也做了db.commit,但我仍然得到这个错误。

您需要使用 .first()

获取查询的第一项
p=Blog.query.filter_by(id=id).first()