Learn Django

New/Edit Contact - Enable AJAX

To prevent unnecessary page refreshe, the account edit link has been configured to fetch the edit form via AJAX. Two changes need to be made in order for this to work. First, we need to update the JavaScript file to intercept the edit link action so that it fetches the form from the server and updates the page without a full page refresh.

Second, we need to update the account_cru() view so that it can detect the request is being made via AJAX. Django comes built in with a handy helper to detect whether AJAX is being used or not. If it is we won't return the whole template; instead we'll just return the elements needed to display

Step 1: Add the JS

Open /.../crmeasy/crmapp/static/js/app.js in your IDE. Add this code to the end.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Main App
$(document).ready(function() {

    // Account - Use AJAX to get the Account Edit form and
    // display it on the page w/out a refresh
    $('#gi-container').delegate('.edit-account', 'click', function(e) {
        e.preventDefault();
        $('#gi-container').load($(this).attr('href'));
    });

});

Code Review

Line 2: Here we create a new function that only executes once the document is ready.

Line 6: Here we use the .delegate() function to assign a click event to the edit link. This is scoped to the #gi-container, where the edit link is located.

Line 7: This statement will prevent the browser from taking the default action of opening the link.

Line 8: Finally, this uses the .load() function to fetch the form from the server and insert it into the #gi-container div.

Step 2: Update the View

There are just a few minor changes to the view. These changes are used to detect if the request is being made via AJAX. Based on this information the view will decide which template file 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
@login_required()
def account_cru(request, uuid=None):

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

    if request.POST:
        form = AccountForm(request.POST, instance=account)
        if form.is_valid():
            form.save()
            redirect_url = reverse(
                'crmapp.accounts.views.account_detail',
                args=(account.uuid,)
            )
            return HttpResponseRedirect(redirect_url)
    else:
        form = AccountForm(instance=account)

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

    if request.is_ajax():
        template = 'accounts/account_item_form.html'
    else:
        template = 'accounts/account_cru.html'

    return render(request, template, variables)

Code Review

Lines 28-31: This is a decision tree that is used to determine if the view is being processed by an AJAX request. If it is AJAX, the method is_ajax() will return True. In that case only the account form should be returned.

If the request is not AJAX then the entire new account page should be returned.

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 "enabled AJAX on edit account form"

Track your progress with a free account