Reputation: 69
I have following simple tag registered in my django 1.7 setup using python 3:
# templatetags/getKonten.py
from django import template
from bilanz.models import Konto
register = template.Library()
def getKonten():
'''Description...'''
konten = Konto.objects.all()
return konten
register.simple_tag(getKonten)
When I try to access the simple tag in the template I only get this output: [, , , ]
. It looks like it's an empty list. But the Konto table is not empty! I want to iterate over all the objects from the query set. This is how I call the template tag in the template:
{% load getKonten %}
{% block content %}
{% getKonten %} <!-- Output: [, , , ] -->
<!-- the for loop below has no output -->
{% for konto in getKonten %}
<h2>{{ konto.konto_title }}</h2>
{% endfor %}
{% endblock %}
Following simple tag works without problem:
from django import template
from bilanz.models import Konto
from bilanz.templatetags.kontoSum import kontoSum
register = template.Library()
def totalSum(kontotype):
konten = Konto.objects.filter(konto_type=kontotype).filter(konto_type2='-')
sum = 0
for konto in konten:
sum += kontoSum(konto.id, konto.konto_type)
return sum
register.simple_tag(totalSum)
I really don't see what the problem is!
UPDATE: This is the models.py:
class Konto(models.Model):
konto_title = models.CharField(max_length=200)
konto_anfangsBestand = models.IntegerField(default=0)
konto_sum = models.IntegerField(default=0)
konto_erfolgswirksam = models.BooleanField(default=False)
konto_types = (
('A', 'Aktiv'),
('P', 'Passiv')
)
konto_types2 = (
('-', 'nicht erfolgswirksam'),
('B', 'Betrieb'),
('F', 'Finanz'),
('N', 'Neutral'),
('S', 'Steuer'),
)
konto_types3 = (
('UV', 'Umlaufvermögen'),
('AV', 'Anlagevermögen'),
('kFK', 'kurzfristiges Fremdkapital'),
('lFK', 'langfristiges Fremdkapital'),
('EK', 'Steuer'),
)
konto_type = models.CharField(max_length=1, choices=konto_types)
konto_type2 = models.CharField(max_length=1, choices=konto_types2, default='-')
konto_type3 = models.CharField(max_length=3, choices=konto_types3)
def __str__(self):
return self.konto_title
Upvotes: 4
Views: 2230
Reputation: 5496
A simple_tag
is meant to return a string
. What you need to use is an assignment_tag
:
@register.assignment_tag
def get_konten():
return Konto.objects.all()
in the template:
{% get_konten as konten %}
{% for konto in konten %}
...
Upvotes: 6