Le-Hao Nguyen
Le-Hao Nguyen

Reputation: 85

Call Django function with argument in html

I am pretty new to django and try to call a django function in html to display how many objects of 'Akte' is in the respective 'Charge' object, but somehow I am missing the right way to do it.

models.py: 
class Charge(models.Model):
    STATI = (
    ('O','Offen'),
    ('G','Geschlossen'),
    )
"Projektnr = models.CharField(max_length=30)"
Containernr = models.CharField(max_length=30)
Plombennr = models.CharField(max_length=30)
status = models.CharField(max_length=1, choices=STATI)
def __str__(self):
    return self.Containernr


class Akte(models.Model):
Aktenbarcode = models.CharField(max_length=30)
"Eincheckdatum = models.datetime()"
user = models.CharField(max_length=30)
containerId = models.ForeignKey(Charge,on_delete=models.CASCADE)
kundennr = models.CharField(max_length=30) 
Startdatum = models.DateField(auto_now_add=True)
def __str__(self):
    return self.Aktenbarcode

and this is my views.py:

def tabelle(request):
assert isinstance(request, HttpRequest)
charge_list = Charge.objects.all()

return render(
    request,
    'app/tabelle.html',
    {

        'charge_list':charge_list,


    }
)

def anzahl(containernr):
    return {'anzahl': Akte.objects.filter(containerId__Containernr==containernr).count }

and here is the html code:

{% extends "app/ats.html" %}

{% block content %}
{% if not user.is_anonymous %}
<div style="margin-left:10%;color:white;"><a style="color:white"href="{%      url 'home'%}">Home</a> ><a style="color:white"> Tabellenübersicht</a></div>
<div>
<table>
    <tr>
        <th>Containernummer</th>
        <th>Status</th>
        <th>Anzahl Akten</th>
        <th>Plombennummer</th>            
        <th></th>     
    </tr>
    {%for Charge in charge_list%}
    <tr>
        <td>{{Charge.Containernr}}</td>
        <td>{{Charge.status}}</td>
        <td>{% anzahl Charge.Containernr %}</td>
        <td>{{Charge.Plombennr}}</td>
</tr>
    {% endfor %}
    </table>

 </div>

 {% endif %}    

{% endblock %}

when I try it, I always get this error: TemplateSyntaxError at /tabelle

Invalid block tag on line 19: 'anzahl(Charge.Containernr)', expected 'empty' or 'endfor'. Did you forget to register or load this tag?

what is the right way to solve this problem?

Upvotes: 1

Views: 309

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You can't call methods with arguments in the template. But you don't need to here; to get the count of Akte for that Charge you can do:

{{ Charge.akte_set.count }}

An even better - and much more efficient - approach is to get this data in the original query in your view, via annotation:

from django.db.models import Count
def tabelle(request):
    charge_list = Charge.objects.all().annotate(akte_count=Count('akte'))

and now in your template you can do:

{{ Charge.akte_count }}

Upvotes: 2

Related Questions