0

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.

Ben the Coder
  • 539
  • 2
  • 5
  • 21

1 Answers1

4

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JLeno46
  • 1,186
  • 2
  • 14
  • 29
  • Would I put this code inside the "if request.method != 'post'" or the else block? Sorry for being so clueless! I'm new to Django. – Ben the Coder Nov 29 '22 at 02:09
  • 1
    You can put it anywhere, use the entry_id parameter you pass to your view to retrieve the object you want to delete and use the .delete() method to delete it. Or use DeleteView like here: https://stackoverflow.com/questions/5531258/example-of-django-class-based-deleteview – JLeno46 Nov 29 '22 at 19:43