I'm in the process of learning Django and I'm currently stuck at creating my own template tags. I'm trying to create something that would create a menu based on a string with menu items. In Django template language, the following would produce what I'm looking for:
{% for item in menu_items %}
{{ item }} {% if not forloop.last %} | {% endif %}
{% endfor %}
Here's what I try to input in a designated templatetags application:
def construct_menu(parser, token):
try:
tag_name, menu_items = token.split_contents()
except ValueError:
msg = '%r tag requires a space separated quote of strings.' % token.split_contents()[0]
raise template.TemplateSyntaxError(msg)
return MenuNode(menu_items[1:-1])
class MenuNode(template.Node):
def __init__(self, menu_items):
self.menu_items = str(self.menu_items)
def render(self, context):
...
register.tag('menu', construct_menu)
And here's the error that I get:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/news/
Django Version: 1.5.1
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'news',
'showroom',
'contact',
'templatetags')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Template error:
In template /Users/per/Documents/Tilde/templates/home.html, error at line 1
'MenuNode' object has no attribute 'menu_items'
1 : {% extends "base.html" %}
2 :
3 : {% block title %}
4 : Home page! :D
5 : {% endblock %}
6 : for post in posts
7 : post
8 : endfor
9 : {% block content %}
10 : This is where the news goes.
11 : {% endblock %}
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/per/Documents/Tilde/news/views.py" in home
6. return render(request, 'home.html')
File "/Library/Python/2.7/site-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/Library/Python/2.7/site-packages/django/template/loader.py" in render_to_string
177. return t.render(context_instance)
File "/Library/Python/2.7/site-packages/django/template/base.py" in render
140. return self._render(context)
File "/Library/Python/2.7/site-packages/django/template/base.py" in _render
134. return self.nodelist.render(context)
File "/Library/Python/2.7/site-packages/django/template/base.py" in render
830. bit = self.render_node(node, context)
File "/Library/Python/2.7/site-packages/django/template/debug.py" in render_node
74. return node.render(context)
File "/Library/Python/2.7/site-packages/django/template/loader_tags.py" in render
102. compiled_parent = self.get_parent(context)
File "/Library/Python/2.7/site-packages/django/template/loader_tags.py" in get_parent
99. return get_template(parent)
File "/Library/Python/2.7/site-packages/django/template/loader.py" in get_template
146. template, origin = find_template(template_name)
File "/Library/Python/2.7/site-packages/django/template/loader.py" in find_template
135. source, display_name = loader(name, dirs)
File "/Library/Python/2.7/site-packages/django/template/loader.py" in __call__
43. return self.load_template(template_name, template_dirs)
File "/Library/Python/2.7/site-packages/django/template/loader.py" in load_template
49. template = get_template_from_string(source, origin, template_name)
File "/Library/Python/2.7/site-packages/django/template/loader.py" in get_template_from_string
157. return Template(source, origin, name)
File "/Library/Python/2.7/site-packages/django/template/base.py" in __init__
125. self.nodelist = compile_string(template_string, origin)
File "/Library/Python/2.7/site-packages/django/template/base.py" in compile_string
153. return parser.parse()
File "/Library/Python/2.7/site-packages/django/template/base.py" in parse
274. compiled_result = compile_func(self, token)
File "/Users/per/Documents/Tilde/templatetags/templatetags/tagtest.py" in construct_menu
34. return MenuNode(menu_items[1:-1])
File "/Users/per/Documents/Tilde/templatetags/templatetags/tagtest.py" in __init__
38. self.menu_items = str(self.menu_items)
Exception Type: AttributeError at /news/
Exception Value: 'MenuNode' object has no attribute 'menu_items'
I'm basically copying the entire thing from http://www.djangobook.com/en/2.0/chapter09.html, but this error doesn't make sense to me. I think I pass all the valid attributes to the relevant places. Any advice?
Many thanks in advance!
The traceback shows you that the error occurs here:
self.menu_items = str(self.menu_items)
But this is the first line of the __init__
method. self.menu_items
doesn't exist yet, because you haven't assigned it. I expect you mean:
self.menu_items = str(menu_items)
(although, since you're presumably going to iterate through menu_items at some stage, I'm not sure why you want to convert it to a string).