Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Custom Inclusion Tags

I'm trying to build my own template tags. I have no idea why I getting these errors. I'm following the Django doc's.

This is my app's file structure:

pollquiz/
    __init__.py
    show_pollquiz.html
    showpollquiz.py

This is showpollquiz.py:

from django import template
from pollquiz.models import PollQuiz, Choice
register = template.Library()

@register.inclusion_tag('show_pollquiz.html')
def show_poll():
    poll = Choice.objects.all()
    return { 'poll' : poll }

html file:

<ul>
{% for poll in poll 
    <li>{{ poll.pollquiz }}</li>
{% endfor 
</ul>

in my base.html file im am including like this

{% load showpollquiz %}
and
{% poll_quiz %}

Bu then I get the the error:

Exception Value: Caught an exception while rendering: show_pollquiz.html

I have no idea why this happens. Any ideas? Please keep in mind I'm still new at Django

like image 626
Harry Avatar asked Mar 03 '10 09:03

Harry


People also ask

What is inclusion tag in Django?

The Django developer can define the custom template tag and filter to the extent the template engine and the new template tag can be used using the {% custom_tag %}. The template tag that is used to display data by rendering another template is called the inclusion tag.

What are Django template tags?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.


Video Answer


2 Answers

Shouldn't all custom filters be inside the templatetags directory?

templatetags/
    __init__.py
    showpollquiz.py

then

@register.inclusion_tag('show_pollquiz.html')

looks in MY_TEMPLATE_DIR/show_pollquiz.html for the template

like image 112
dotty Avatar answered Sep 30 '22 17:09

dotty


You forgot to close your template tags... Also, you should change the name in the for tag, you can't have for poll in poll:

<ul>
{% for p in poll %} <!--here-->
    <li>{{ p.pollquiz }}</li>
{% endfor %} <!--and here-->
</ul>

Also notice you're not using the inclusion tag you defined at all. I think you got some code mixed up, try to go over a tutorial start to end and things will be clearer.

like image 20
Yuval Adam Avatar answered Sep 30 '22 18:09

Yuval Adam