Уведомления

Группа в Telegram: @pythonsu

#1 Авг. 15, 2014 15:50:10

snitkoff
Зарегистрирован: 2014-05-13
Сообщения: 9
Репутация: +  0  -
Профиль   Отправить e-mail  

Шаблонный тег с django-mptt

Всем привет!!! Перерыл кучу сайтов но правильного решения проблемки так и не нашел. У меня есть простая модель категорий

class Category(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    def __str__(self):
        return self.name

Дерево категорий должно отображаться на всех страницах сайта. т.е. нужно создать шаблонный тег и впилить его в базовый шаблон. Делаю следующее:
В папке templatetags приложения создаю файл category_tegs.py и в нем
from django import template
from django.core.context_processors import request
from django.shortcuts import render_to_response
from django.template import RequestContext
from apps.core.models import Category
register = template.Library()
@register.inclusion_tag('category_tree.html', takes_context=True)
def show_category():
    category = Category.objects.all()
    return render_to_response ('category_tree.html', {'nodes': category}, context_instance=RequestContext(request))

Далее создаю шаблон category_tree.html

{% load category_tags %}
{% load mptt_tags %}
<ul>
    {% recursetree nodes %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>

Ну и в шаблон сам тег {% show_category %}
В результате получаю
Traceback:
File "/django_projects/hm/env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/django_projects/hm/hm/apps/core/views.py" in main_page
  17.     return render_to_response('index.html', args)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/shortcuts/__init__.py" in render_to_response
  29.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in render_to_string
  164.         return t.render(Context(dictionary))
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in render
  140.             return self._render(context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in _render
  134.         return self.nodelist.render(context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in render
  840.                 bit = self.render_node(node, context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/debug.py" in render_node
  78.             return node.render(context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader_tags.py" in render
  101.         compiled_parent = self.get_parent(context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader_tags.py" in get_parent
  98.         return get_template(parent)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in get_template
  138.     template, origin = find_template(template_name)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in find_template
  127.             source, display_name = loader(name, dirs)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in __call__
  43.         return self.load_template(template_name, template_dirs)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in load_template
  49.             template = get_template_from_string(source, origin, template_name)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in get_template_from_string
  149.     return Template(source, origin, name)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in __init__
  125.         self.nodelist = compile_string(template_string, origin)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in compile_string
  153.     return parser.parse()
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in parse
  278.                     compiled_result = compile_func(self, token)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in generic_tag_compiler
  1025.                               defaults, takes_context, name)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in parse_bits
  959.         if params[0] == 'context':
Exception Type: IndexError at /
Exception Value: list index out of range

Подскажите, пожалуйста, что я делаю не правильно….?

Офлайн

#2 Авг. 15, 2014 17:44:54

ilnur
От: Казань
Зарегистрирован: 2009-01-06
Сообщения: 524
Репутация: +  22  -
Профиль   Отправить e-mail  

Шаблонный тег с django-mptt

функция не принимает параметров. хотя вроде должен принимать контекст. и в возращаемом результате у вас реквест, хотя должен быть контекст

Офлайн

#3 Авг. 18, 2014 14:00:31

snitkoff
Зарегистрирован: 2014-05-13
Сообщения: 9
Репутация: +  0  -
Профиль   Отправить e-mail  

Шаблонный тег с django-mptt

Ок… Изменил на…

from django import template
from django.shortcuts import render_to_response
from apps.core.models import Category
register = template.Library()
@register.inclusion_tag('category_tree.html', takes_context=True)
def show_category(context):
    category = Category.objects.all()
    return render_to_response('category_tree.html', {'nodes': category}, context_instance=context)

Получаю…

Traceback:
File "/django_projects/hm/env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/django_projects/hm/hm/apps/core/views.py" in main_page
  34.     return render_to_response('index.html', args)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/shortcuts/__init__.py" in render_to_response
  29.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in render_to_string
  164.         return t.render(Context(dictionary))
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in render
  140.             return self._render(context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in _render
  134.         return self.nodelist.render(context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in render
  840.                 bit = self.render_node(node, context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/debug.py" in render_node
  78.             return node.render(context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader_tags.py" in render
  101.         compiled_parent = self.get_parent(context)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader_tags.py" in get_parent
  98.         return get_template(parent)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in get_template
  138.     template, origin = find_template(template_name)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in find_template
  127.             source, display_name = loader(name, dirs)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in __call__
  43.         return self.load_template(template_name, template_dirs)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in load_template
  49.             template = get_template_from_string(source, origin, template_name)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/loader.py" in get_template_from_string
  149.     return Template(source, origin, name)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in __init__
  125.         self.nodelist = compile_string(template_string, origin)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in compile_string
  153.     return parser.parse()
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in parse
  278.                     compiled_result = compile_func(self, token)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in generic_tag_compiler
  1025.                               defaults, takes_context, name)
File "/django_projects/hm/env/lib/python3.4/site-packages/django/template/base.py" in parse_bits
  959.         if params[0] == 'context':
Exception Type: IndexError at /
Exception Value: list index out of range

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version