Learn Django

New/Edit Comm - Enable AJAX

The new/edit communication functionality requires the use of AJAX on the account detail page. This consists of modifying the comm_cru() view and adding some JS to our app.js file.

Step 1: Add JavaScript

The first step is to add several functions to the JavaScript app. Review the comments in the code below to understand what each function does.

Open /.../crmeasy/crmapp/static/js/app.js, locate the // Main App section, and add the following code within the function (below the code that already exists).

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Main App
$(document).ready(function() {
    ...

    // Communications - When the Subject of the form is clicked, the whole form is displayed
    $('#co-container').delegate('#id_subject', 'focus', function() {
        $('#comm-form-internals').show();
    });


    // Communications - Use AJAX to get the Communications Add Form
    $('#co-container').delegate('#new-comm', 'click', function(e) {
        e.preventDefault();
        $.get($(this).attr('href'), function(data) {
            $('#co-list').prepend(data);
        })
    });


    // Communications - Use AJAX to get the Comm Edit Form
    $('#co-container').delegate('.comm-edit', 'click', function(e) {
        e.preventDefault();
        var that = $(this);
        $.get($(this).attr('href'), function(data) {
            $('#co-body').find('#comm-form').remove();
            $('#co-form-wrapper').append(data);
            $('#comm-form-internals').show();
            that.parent().parent().parent().remove();
        })
    });


    // Communications - Use AJAX to save the Comm Add Form
    $('#co-container').delegate('#comm-form', 'submit', function(e) {
        e.preventDefault();
        var form = $('#comm-form');
        var url = form.attr('action');
        $.post(url, form.serialize(), function(data) {
            if ($(data).find('#comm-form-internals').html()) {
                // If form comes back then display it properly
                form.remove();
                $('#co-form-wrapper').prepend(data); // Appends the newly created Communication
                $('#comm-form-internals').show(); // Make sure it shows
                $('#comm-form').attr('action', '/comm/new/'); // Make sure the action is set to new
            } else {
                // When is this supposed to kick in?
                resetForm($('#comm-form')); // Resets the form values
                $('#comm-form').find('ul').remove(); // If there are any errors on the form, remove them all
                $('#comm-form-internals').hide(); // Hides everything but the subject
                $('#co-list').prepend(data); // Appends the newly created Communication
                $('#comm-form').attr('action', '/comm/new/'); // Make sure the action is set to new
            }
        })
    });

});

Step 2: Modify the View

The below view should look very familiar. It will stay the same with the exception of two modifications. The first one starts on line 21 where we check to see if this request is made by AJAX. If it is only the communication item template is returned, instead of the whole page.

The second change starts on line 47. Again, a check is made for AJAX to determine which template to return.

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@login_required()
def comm_cru(request, uuid=None, account=None):

    if uuid:
        comm = get_object_or_404(Communication, uuid=uuid)
        if comm.owner != request.user:
            return HttpResponseForbidden()
    else:
        comm = Communication(owner=request.user)

    if request.POST:
        form = CommunicationForm(request.POST, instance=comm)
        if form.is_valid():
            # make sure the user owns the account
            account = form.cleaned_data['account']
            if account.owner != request.user:
                return HttpResponseForbidden()
            # save the data
            form.save()
            # return the user to the account detail view
            if request.is_ajax():
                return render(request,
                              'communications/comm_item_view.html',
                              {'comm':comm, 'account':account}
                )
            else:
                reverse_url = reverse(
                    'crmapp.contacts.views.account_detail',
                    args=(account.uuid,))
                return HttpResponseRedirect(reverse_url)
        else:
            # if the form isn't valid, still fetch the account so it can be passed to the template
            account = form.cleaned_data['account']
    else:
        form = CommunicationForm(instance=comm)

    # this is used to fetch the account if it exists as a URL parameter
    if request.GET.get('account', ''):
        account = Account.objects.get(id=request.GET.get('account', ''))

    variables = {
        'form': form,
        'comm':comm,
        'account': account
    }

    if request.is_ajax():
        template = 'communications/comm_item_form.html'
    else:
        template = 'communications/comm_cru.html'

    return render(request, template, variables)

Step 3: 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 "added AJAX to communication"

Track your progress with a free account