Reputation: 59
I am having trouble with my page redirect when deleting a users comment. below is my code. It deletes the message but gives me this error: Message matching query does not exist for Message.objects.get(id=message_id).delete().
def remove_message(request, message_id):
Message.objects.get(id=message_id).delete()
return redirect(reverse('dashboard:show'))
^ABOVE FIXED:
new issue, cannot get my delete button to show when trying to delete only the current users comments. Code below:
views.py
def remove_message(request, user_id, message_id):
user = User.objects.get(id=request.session['user_id'])
Message.objects.filter(id=message_id, user = request.user).delete()
return redirect(reverse('dashboard:show', args=user_id))
show.html
{% for message in messages%}
<div class="message">
<p class='bg-primary wall_content'><strong>{{message.messageuser.first_name}} wrote:</strong></p>
<p class='wall_content'>{{message.message}}</p>
{% if message.id == request.user %}
<a href='{% url "dashboard:remove_message" user.id message.id %}'>Delete Message</a>
{% endif %}
{% for comment in comments %}
{% if message.id == comment.message.id %}
<p class='bg-success wall_content comment'><strong>{{comment.user.first_name}} wrote:</strong></p>
<p class='wall_content comment'>{{comment.comment}}</p>
{% endif %}
{% endfor %}
Upvotes: 1
Views: 33
Reputation: 369354
Instead of get
, you can use filter
which returns QuerySet
. Unlike the get
method, the filter
does not raise ObjectDoesNotExist
exception, but just returns a empty queryset if there's no matching object.
Deleting empty queryset has no harm.
So you the line can be replaced with:
Message.objects.filter(id=message_id).delete()
Upvotes: 2