我是创建Web应用程序的新手,我决定从学习Flask开始。我正在建立一个社交网络作为练习和学习一些基本技能的辅助项目。
到目前为止,我已经能够建立一个用户可以发布的“流”,有点像Twitter。 我一直在努力寻找一种方法来允许用户删除帖子。我正在使用带有Peewee库的SQLite数据库。这是我尝试过的:
@app.route('/delete_post/<int:post_id>')
@login_required
def delete_post(post_id):
delete = models.Post.select().where(models.Post.id == post_id)
try:
models.DATABASE.delete(delete)
except models.DoesNotExist:
abort(404)
else:
flash("This post has successfully been deleted.", "success")
return redirect(url_for('stream', stream = stream))
此外,以下是帖子的创建方式:
class Post(Model):
timestamp = DateTimeField(default=datetime.datetime.now())
user = ForeignKeyField(
rel_model= User,
related_name='posts'
)
content = TextField()
class Meta:
database = DATABASE
order_by = ('-timestamp',)
最后,有一个模板,当用户选择“删除”时,将调用delete_post方法
{% extends "base.html" %}
{% block content %}
{% for post in stream %}
<article>
<h2>
<a href="{{ url_for('stream', username=post.user.username) }}">{{ post.user.username }}</a>
</h2>
<i class="clock"></i>
<time>
{{ post.timestamp.strftime("%a, %d %b %Y %H:%M") }}
</time>
<a href="{{ url_for('view_post', post_id=post.id) }}" class="view">View</a>
<a href="{{ url_for('delete_post', post_id=post.id) }}" class="view" >| Delete</a>
<div class="post">
{{ post.content }}
</div>
</article>
{% endfor %}
{% endblock %}
如何删除帖子?当我尝试使用我的解决方案时,我得到:AttributeError: 'SqliteDatabase' object has no attribute 'delete'
我知道这个问题非常冗长,但任何帮助都会非常感激,并会在未来的项目中帮助我很多。如果我需要澄清其他任何内容,请告诉我。
谢谢!
答案 0 :(得分:1)
要删除:
def delete_post(post_id):
try:
post = models.Post.select().where(models.Post.id == post_id).get()
except models.Post.DoesNotExist:
abort(404)
post.delete_instance()
flash("This post has successfully been deleted.", "success")
return redirect(url_for('stream', stream = stream))
或者,你可以写:
def delete_post(post_id):
post = models.Post.delete().where(models.Post.id == post_id).execute()
flash("This post has successfully been deleted.", "success")
return redirect(url_for('stream', stream = stream))
编辑:我还想向您指出涵盖各种主题的文档...... http://docs.peewee-orm.com/en/latest/peewee/querying.html#deleting-records