Day Log App in Django Part 6: Delete a DayLog

This post will discuss how to delete a Daylog.

Table of Contents

Steps

Create test

The tests will check for a valid slug parameter before deletion.

def test_delete_existing_daylog(self):
    daylog = create_daylog()
    daylog.save()

    self.assertTrue(Daylog.objects.filter(slug = daylog.slug).count())

    response = self.client.post(reverse('daylog:delete', args=(daylog.slug,)), follow=True)

    self.assertFalse(Daylog.objects.filter(slug = daylog.slug).count())

    for message in response.context['messages']:
        self.assertEqual(message.message, "Day Log deleted.")
        self.assertEqual(message.extra_tags, "info")
        break;

def test_delete_nonexistent_daylog(self):
    nonexistent_slug = "non-existent-slug"

    self.assertFalse(Daylog.objects.filter(slug = nonexistent_slug).count())

    response = self.client.post(reverse('daylog:delete', args=(nonexistent_slug,)), follow=True)

    for message in response.context['messages']:
        self.assertEqual(message.message, "Day Log does not exist.")
        self.assertEqual(message.extra_tags, "danger")
        break;

Set URL

The URL for delete will be the slug followed by the word “delete”:

url(r'^(?P<slug>.+)/delete$', views.delete, name='delete'),

Create delete method

The delete method will use the redirect method after a successful deletion in order to prevent repetition in case the back feature of browsers is used.

from django.shortcuts import redirect, render
...
def delete(request, slug):
    try:
        daylog = Daylog.objects.get(slug = slug)
    except Daylog.DoesNotExist:
        messages.error(request, "Day Log does not exist.", "danger")
        return redirect('daylog:get_list')

    daylog.delete()
    messages.error(request, "Day Log deleted.", "info")
    return redirect('daylog:get_list')

Update delete form

Go to templates/daylog/index.html and change the delete form from:

<form action="/daylog//delete" method="POST">
    <input type='hidden' value='DELETE' name='_method'>

to


<form action="{% url 'daylog:delete' daylog.slug %}" method="POST">
    {% csrf_token %}

References

Twitter, LinkedIn