Delete an object

Question:

Looking to delete an object in Django, but none of the other Stack Overflow questions fix my issue. Looked at this one, but it doesn’t seem to be working. My delete object code (in the views file) looks like this:

@login_required
def delete_entry(request, entry_id):
    """Delete an existing entry."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = TopicForm()
    else:
        # POST data submitted; process data.
        form = TopicForm(data=request.POST)
        if form.is_valid():
            new_topic = form.delete(commit=False) ### Code to delete object
            new_topic.owner = request.user
            new_topic.save()
            return redirect('learning_logs:topics')

    # Display a blank or invalid form.
    context = {'topic': topic, 'form': form}
    return render(request, 'learning_logs/new_entry.html', context)

And in URLs.py:

path('delete_entry/<int:entry_id>', views.delete_entry, name='delete_entry'),

I would like to use a Bootstrap 4 button (inside a modal) to delete the entry (so without any redirects to another confirmation page),

Screenshot

Unfortunately, this isn’t working. I’m just getting a server error saying that NoReverseMatch at /delete_entry/6.

Using Python 3.

Asked By: Ben the Coder

||

Answers:

It seems like you’re trying to call the delete method on the form. If you want to delete the object, you should call it on the object:

my_object = MyModel.objects.get(id=entry_id) # Retrieve the object with the specified id
my_object.delete() # Delete it

Here is the relevant Django documentation.

I think that you’re looking for a DeleteView.

Answered By: JLeno46