Learn Django

Delete Comm - Full Lesson

The last step is to create the delete communication functionality. This is very similar to the delete contact functionality. To recap, a CBV will be created to process the deletion requests. Second, a URL will be created to provide access to the delete action. Lastly, we'll add the delete URL to the template.

Step 1: Create the Views

Open /.../crmeasy/crmapp/communications/views.py, add the imports to the top of the file, and then add the two views to the bottom. These views will process the delete communication requests.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from django.utils.decorators import method_decorator
from django.views.generic.edit import DeleteView
from django.http import Http404

class CommMixin(object):
    model = Communication

    def get_context_data(self, **kwargs):
        kwargs.update({'object_name':'Communication'})
        return kwargs

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(CommMixin, self).dispatch(*args, **kwargs)

class CommDelete(CommMixin, DeleteView):
    template_name = 'object_confirm_delete.html'

    def get_object(self, queryset=None):
        obj = super(CommDelete, self).get_object()
        if not obj.owner == self.request.user:
            raise Http404
        account = Account.objects.get(id=obj.account.id)
        self.account = account
        return obj

    def get_success_url(self):
        return reverse(
            'crmapp.accounts.views.account_detail',
            args=(self.account.uuid,)
        )

Step 2: Create The URL Configuration

The app will process delete requests at the /comm/delete/ URL. Open the /.../crmeasy/crmapp/urls.py file. Add the import and URL configuration below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from communications.views import CommDelete

# Communication related URLs
url(r'^comm/new/$',
    'crmapp.communications.views.comm_cru', name='comm_new'
),
url(r'^comm/(?P<uuid>[\w-]+)/', include(comm_urls)),
url(r'^comm/(?P<pk>[\w-]+)/delete/$',
    CommDelete.as_view(), name='comm_delete'
),

Step 3: Add the Delete URL to the Template

Lastly, we can add the delete URL to the template. Open /.../crmeasy/crmapp/templates/communications/comm_item_view.html. Locate the link below and update the href attribute.

1
2
3
{# Comm Delete URL #}
<a class="cancel comm-control"
   href="{{ comm.get_delete_url }}?account={{ account.id }}"></a>

Step 4: Commit Changes

Execute these commands to commit your changes in Git.

1
2
3
4
5
# add files
(venv)$ git add .

# commit files
(venv)$ git commit -m "created communication delete functionality"

Track your progress with a free account