Herramientas de usuario

Herramientas del sitio


wiki2:python:django:templates

¡Esta es una revisión vieja del documento!


Django Templates

Basic

Configure global template directories

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates/'],
        ...

Render a template

import django.template.loader as loader
temp = loader.get_template('base.html')
return HttpResponse(temp.render())

Puedes añadir una template al directorio templates de la APP. Entonces símplemente has de hacer loader.get_template('the_concrete.html').

Call the super block

{% block submit_buttons_bottom %}
    {{ block.super }}
    ...

Advanced

Varios formularios

Necesitarás generar el id para cada uno de ellos. Para eso usaremos la propiedad auto_id:

def get_context_data(self, **kwargs):
 return super().get_context_data(
    password_change_form=PasswordChangeForm(self.request.user),
    user_data_form=UserDataForm(instance=self.request.user),
    pledge_forms=[
      SignPledgeForm(instance=pledge, auto_id=f'{idx}_%s') 
      for idx, pledge in enumerate(self.request.user.pledges.all())
    ]
)

Con este ejemplo cogerán el patrón indicado.

Tips

Index of the loop

{% for pledge_form in pledge_forms %}
<form method="post" class="generated-form" id="form-{{forloop.counter}}">
...

Numeric loop

{% for work in "xxx" %}

{% endfor %}

Not repeat code

Add a template in openawards/reusable/worklist.html:

<div>hola</div>

Then in another:

{% for work in "xxx" %}
{% include 'openawards/reusable/worklist.html' %}
{% endfor %}

You even can send parameters:

{% include 'worklist.html' with var_a='abc' var_b=123 %}

Debugging templates

If DEBUG is enabled, there's a template tag called {% debug %}

There are some snippets to add:

<pre> {% filter force_escape %} {% debug %} {% endfilter %} </pre>
<textarea onclick="this.focus();this.select()" style="width: 100%;"> {% filter force_escape %} {% debug %} {% endfilter %}</textarea>
wiki2/python/django/templates.1550583557.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)