Learn Django

List Accounts - Create/Update Templates

The account list template is used to display the accounts in a list view. The list will give the account name which is hyperlinked to the account's detail view (yet to be built). Next to the account name will be the date that the account was created.

Follow the steps below to create the template.

Step 1: Create the Template File

Follow these steps to create the template file.

  1. Navigate to ```/.../crmeasy/crmapp/templates'
  2. In this folder create a folder named accounts
  3. In this folder create a file named account_list.html

Step 2: Write the Template

Write this code into the account_list.html file.

 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
{% extends 'base.html' %}
{% block title %}Account List{% endblock title %}

{% block content %}
    <div id="content-container" class="container p-none">
        <div id="al-container" class="side-p">
            <div id="al-control">
                <h3 class="ad-mh">Account List
                    {# Add Account Link #}
                </h3>
                {# Account Search Form #}
            </div>
            {# List of Accounts #}
            <ul id="al-group" class="strip-list">
                {% for account in accounts %}
                    <li class="al-item">
                        <a href=""><h4 class="al-name">{{ account.name }}</h4></a>
                        <span class="al-created">created on {{ account.created_on }}</span>
                    </li>
                {% endfor %}
            </ul>
            {# Pagination Section #}
        </div>
    </div>
{% endblock content %}

Code Review

As with the other templates, most of this code is HTML, which won't be explained here in the Code Review. What will be explained are the unique Django template related portions.

Lines 15-20: This code block is a for loop, which is one of the Django template tags available. Here we iterate over each account in the accounts object (which was passed to this template via the AccountList view). For each account in the list, several HTML elements are created, including a <li>, an <a>, etc. This for loop is responsible for generating the list of accounts that you see on the page.

Now that the Account List has been created it's time to update the navigation link the base.html file.

Step 3: Update the Base.html File

Follow these steps to update the file.

  1. Open the /.../crmeasy/crmapp/templates/base.html file
  2. Locate the following line and update it as follows
1
2
3
4
5
6
7
# Old code
<li><a href=""
       class="p-r-none">Accounts</a></li>

# New code
<li><a href="{% url 'account_list' %}"
       class="p-r-none">Accounts</a></li> 

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 account list template; updated base with link"

Track your progress with a free account