I am new to creating web applications, and I decided to start out by learning Flask. I am making a Social Network as a side-project to practice and learn some basic skills.
So far, I have been able to build a "Stream" that users can post to, kind of like Twitter. I have been struggling to find a way to allow users to Delete posts. I am using a SQLite database with the Peewee library. Here is what I have tried:
@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))
Also, here is how a Post is created:
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',)
Finally, there is the template where the delete_post method would be called when the use selects "Delete"
{% 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 %}
How do I go about deleting a post? When I try my solution I get: AttributeError: 'SqliteDatabase' object has no attribute 'delete'
I know this question is pretty long-winded, but any help would be much appreciated and would help me a lot in future projects. Let me know if I need to clarify anything else.
Thanks!
To delete:
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))
Alternatively, you can write:
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))
Edit: I also just want to point you to the docs, which cover all sorts of topics... http://docs.peewee-orm.com/en/latest/peewee/querying.html#deleting-records