Django – Templates y Ficheros Estáticos

Templates:

Configuracion:

# settings.py

TEMPLATES = [
    {
        ...
        'DIRS': [
            BASE_DIR / "templates"
        ],
        ...
        'APP_DIRS': True,
        ...
    }
]

Ubicación:

./app/templates/app/modelo/template.html    --> de la app
./templates/app/modelo/template.html    --> globales

Carga:

from django.template.loader import render_to_string
from django.shortcuts import render
from django.http import HttpResponse

def fn_view(request, ...):
    ...
    response = render_to_string("app/modelo/template.html")
    ...
    return HttpResponse(response)
    return render(request, "app/modelo/template.html", {'var1': val1, 'var2': val2, ...})

DTL – Django Template Language

{{ var_2_display }}
{{ var|filtro:param}}
{% tag parametros %} ... {% endtag %}

Filtro: función que se pueden aplicar a las variables: https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#ref-templates-builtins-filters

Tag: permite funcionalidades por bloques de códigos: https://docs.djangoproject.com/es/5.1/ref/templates/builtins/#built-in-tag-reference

URLS

{% url 'nombre_de_url' %}
{% url 'nombre_de_url' val_1 val_2 %}
{% url 'nombre_de_url' param1=val1 param2_val2 %}
{% url 'nombre_de_url' val_1 val_2 as the_url_var %}

Herencia de Templates

<!-- base.html -->
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block bloque_1 %}Contenido Default{% endblock %}</title>
</head>
<body>
    {% block bloque_2 %}
        Contenido Default 2
    {% endblock %}
</body>
</html>
<!-- heredado.html -->
{% extends base.html %}

{% block bloque_1 %}Mí contenido en este template{% endblock %}

{% block bloque_2 %}
    Contenido del bloque 2
{% endblock %}

Inclusion parcial de Templates (include)

<!-- parcial.html -->
<header>
    <nav>
        Contenido ejemplo a incluir
    </nav>
</header>
<!-- heredado.html -->
{% extends base.html %}

{% block bloque_1 %}Mí contenido en este template{% endblock %}

{% block bloque_2 %}
    {% include "parcial.html" %}
    Contenido del bloque 2
{% endblock %}

Templates 404

<!-- 404.html -->

Contenido del HTML a mostrar en caso 404 Not Found
from django.http import Http404

def fn_view(request, ...):
    ...
    raise Http404() # Automáticamente busca 404.html 
                    # cuando el setting.DEBUG = False

Archivos Estáticos

Ubicación

./app/static/app/archivo_js_css.ext    --> de la app
./static/app/archivo_js_css.ext    --> globales
# settings.py

INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
    ...
]

...
STATIC_URL = '/static/'
...
STATICFILES_DIRS = [
    ...
    BASE_DIR / "static"
    ...
]
...

Carga de archivos estaticos

<!-- template.html -->
{% load static %}

...
<link rel="stylesheeet" href="{% static "app/archivo.css" %}" />
...