0

Working in a Django Project. I have an index.html file with a variable called "todas_academias", which is a list of models classes that I've created. Directory: FKSC/ac_filiados/templates/ac_filiados/index.html

{% for academia in ordenar(todas_academias) %}
                 <td>{{ academia.nome_academia }}</td>
                 <td>{{ academia.estado }}</td>
                 <td>{{ academia.cidade }}</td>
                 <td>{{ academia.professor }}</td>
                 <td>{{ academia.num_alvara }}</td>
{% endfor %}

And I created a function called "ordenar" in a python file in another directory. Directory: FKSC/ac_filiados/functions.py

You DON'T NEED to understand what this function does.

def ordenar(todas_academias):
    lista = []
    for academia in todas_academias:
        lista = lista + [academia.num_alvara]
    nova_list = lista.sort()
    nova_lista_academias = []
    for reg in nova_list:
        for academia in todas_academias:
            if reg == academia.num_alvara:
                nova_lista_academias = nova_lista_academias + [academia]
    return nova_lista_academias 

Now, I just want to use the "ordenar()" function in the index.html file, as I tried to use, but it didn't work. 1) Do I need to import the "ordenar" function before using it? If so, How do I import it? 2) Should I've placed the "ordenar" function in views.py? 3) Or, is there a specific way of using this kind of functions in HTML files?

2 Answers 2

3

You shouldn't call a function from the template. I would pass what ordenar returns via context dictionary to the view like so:

views.py

def ordenar(todas_academias):
    lista = []
    for academia in todas_academias:
        lista = lista + [academia.num_alvara]
    nova_list = lista.sort()
    nova_lista_academias = []
    for reg in nova_list:
        for academia in todas_academias:
            if reg == academia.num_alvara:
                nova_lista_academias = nova_lista_academias + [academia]
    return nova_lista_academias 

def some_view(request):
    ...
    YOUR OTHER CODE
    ...
    return render(request, 'yourtemplate.html', {ordenar: 'ordenar'})

Then in your template you would keep the same code more or less:

{% for academia in ordenar %}
    <td>{{ academia.nome_academia }}</td>
    <td>{{ academia.estado }}</td>
    <td>{{ academia.cidade }}</td>
    <td>{{ academia.professor }}</td>
    <td>{{ academia.num_alvara }}</td>
{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

1

You can add result of your function inside the context of your view or create django template tag inclusion-tags doc and example: custom-inclusion-tags

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.