Day Log App in Django Part 4: Project view templates

As the project grows there is a need to re-use template files across Django applications. This post will show a way to declare templates for global use in the project.

Table of Contents

Steps

In the previous posts, templates are declared in the path app_name/templates/app_name/index.html and they are extended in other template files as app_name/index.html.

Setup

The way in Django 1.8 and above is to simply:

  1. Declare a common directory path in the DIRS key

    Go to api/settings.py and there should be the TEMPLATES variable.

    I added the path below.

    'DIRS': [(os.path.join(BASE_DIR, 'templates')),],
    
  2. Create the templates folder in the same level as all the applications.

Refactor base.html

Currently base.html is inside the daylog application’. In the future, in case other applications need it, just transfer it inside the new templates folder and call in the other template files as:


{% extends 'base.html' %}

Setup alerts

Create the file alert.html in the new templates folder:

<div class="alert alert-" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    
</div>

This layout follows the Bootstrap 4 Alerts module. It expects type and message variables. A striptags filter was added in case the returned message has any.

base.html

There were Django flash messages used in the views.py methods that were set.

In base.html, in orderto show an alert for every CRUD process, add the following block before {% block content %}.


{% if messages %}
    {% for message in messages|slice:":1" %}
        {% include "alert.html" with type=message.extra_tags  message=message %}
    {% endfor %}
{% endif %}

This will expect a variable messages that will contain a single message (hence the :1 slice filter).

Home page with create alert

Additionally the form validation errors from Django should be shown as well in case the HTML5 interface fails. In templates/daylog/form.html, each errors variable from the ModelForm is expected:


{% if errors.title %}
    {% include "alert.html" with type='danger' message=errors.title %}
{% endif %}

Create page with error alerts

References

Twitter, LinkedIn