Custom Django Include Tags

I am trying to create my own template tags. I have no idea why I get these errors. I follow the django docs.

This is my application 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, including how is it

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

Bu, then I get the error:

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

I have no idea why this is happening. Any ideas? Please keep in mind that I'm still new to Django

+4
source share
4 answers

Are all user filters in templatetags?

 templatetags/ __init__.py showpollquiz.py 

then

 @register.inclusion_tag('show_pollquiz.html') 

looks in MY_TEMPLATE_DIR / show_pollquiz.html for the template

+8
source

You forgot to close the template tags ... In addition, you must change the name in the for tag, you cannot have for poll in poll :

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

Also note that you are not using the inclusion tag that you defined at all. I think you messed up the code a bit, try switching over the tutorial to get started, and everything will be clearer.

+3
source

I would not write my own template tags: do something one at a time and stick to the basics. There is nothing wrong with {% include 'show_pollquiz.html' %}

0
source

I found a problem. The problem was that the @ register.inclusion_tag ('show_pollquiz.html') inclusion tag explicitly looked for a template in the default_template directory. That is why I got the error.

For me, this is not clear in the documentation. But I think it’s like a template, and that’s it ...

Oh, OK.

Now, how would I put @ register.inclusion_tag ('show_pollquiz.html') in the same folder as the application? under templatetags /?

0
source

Source: https://habr.com/ru/post/1302963/


All Articles