Git Product home page Git Product logo

idlesign / django-sitetree Goto Github PK

View Code? Open in Web Editor NEW
347.0 14.0 135.0 1.14 MB

Reusable application for Django introducing site tree, menu and breadcrumbs navigation elements.

Home Page: http://github.com/idlesign/django-sitetree

License: BSD 3-Clause "New" or "Revised" License

Python 86.70% HTML 12.73% CSS 0.57%
python django navigation sitetree breadcrumbs menu menu-navigation menu-generator

django-sitetree's Introduction

django-sitetree

http://github.com/idlesign/django-sitetree

release lic coverage

What's that

django-sitetree is a reusable application for Django, introducing site tree, menu and breadcrumbs navigation elements.

Site structure in django-sitetree is described through Django admin interface in a so called site trees. Every item of such a tree describes a page or a set of pages through the relation of URI or URL to human-friendly title. Eg. using site tree editor in Django admin:

URI             Title
  /             - Site Root
  |_users/      - Site Users
    |_users/13/ - Definite User

Alas the example above makes a little sense if you have more than just a few users, that's why django-sitetree supports Django template tags in item titles and Django named URLs in item URIs. If we define a named URL for user personal page in urls.py, for example, 'users-personal', we could change a scheme in the following way:

URI                           Title
  /                           - Site Root
  |_users/                    - Site Users
    |_users-personal user.id  - User Called {{ user.first_name }}

After setting up site structure as a sitetree you should be able to use convenient and highly customizable site navigation means (menus, breadcrumbs and full site trees).

User access to certain sitetree items can be restricted to authenticated users or more accurately with the help of Django permissions system (Auth contrib package).

Sitetree also allows you to define dynamic trees in your code instead of Admin interface. And even more: you can combine those two types of trees in more sophisticated ways.

Documentation

http://django-sitetree.readthedocs.org/

django-sitetree's People

Contributors

clincher avatar daevaorn avatar dependabot[bot] avatar dpretty avatar embreinhardt avatar idlesign avatar jefftriplett avatar jgadelange avatar jonkiparsky avatar kishorkunal-raj avatar kiwnix avatar martey avatar msuszko avatar paltman avatar petrdlouhy avatar pitervergara avatar pws21 avatar ramonsaraiva avatar richardjprice avatar sanjaz avatar scotteadams avatar silveron avatar slav0nic avatar slepa avatar stop5 avatar thenewguy avatar toitayuka avatar voronind avatar vosi avatar wlorenzetti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-sitetree's Issues

SiteTreeError while rendering Sitetree needs "django.core.context_processors.request" template processor

While trying to use sitetree_breadcrumbs in a template:

Caught SiteTreeError while rendering: Sitetree needs "django.core.context_processors.request" template processor to be enabled. Please add it to TEMPLATE_CONTEXT_PROCESSORS in your settings file.
Django Version: 1.3 SVN-16286
Exception Type: TemplateSyntaxError
Exception Value: Caught SiteTreeError while rendering: Sitetree needs "django.core.context_processors.request" template processor to be enabled. Please add it to TEMPLATE_CONTEXT_PROCESSORS in your settings file.
Exception Location: django-sitetree\sitetree\sitetreeapp.py in get_tree_current_item, line 133
Python Version: 2.7.1

However, django.core.context_processors.request is definitely in TEMPLATE_CONTEXT_PROCESSORS as further down on the debug output it shows it listed in the settings that are spit out:

TEMPLATE_CONTEXT_PROCESSORS
('django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.request')

Sitetree throws an exception when trying to use the admin interface on django 1.3

Sitetree throws the following exception when trying to access a specific sitetree in the admin interface:

TemplateSyntaxError at /admin/sitetree/tree/1/

Caught KeyError while rendering: 'request'

Here is the full traceback:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/admin/sitetree/tree/1/

Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.sites',
 'django.contrib.flatpages',
 'tagging',
 'reversion',
 'south',
 'sitetree',
 'dojango',
 'website.blog',
 'website.cms']
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',
 'dojango.middleware.DojoCollector',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware')


Template error:
In template c:\python27\lib\site-packages\sitetree\templates\admin\sitetree\tree\change_form.html, error at line 44
   Caught KeyError while rendering: 'request'
   34 :                     <th width="1%">{% trans "Hidden" %}</th>


   35 :                     <th width="1%">{% trans "Menu" %}</th>


   36 :                     <th width="1%">{% trans "Breadcrumbs" %}</th>


   37 :                     <th width="1%">{% trans "Tree" %}</th>


   38 :                     <th width="25%">{% trans "Title" %}</th>


   39 :                     <th width="20%">{% trans "URL" %}</th>


   40 :                     <th>{% trans "Sort order" %}</th>


   41 :                 </tr>


   42 :             </thead>


   43 :             <tbody>


   44 :                  {% sitetree_tree from "original.alias" template "admin/sitetree/tree/tree.html" %} 


   45 :             </tbody>


   46 :         </table>


   47 :     </div>


   48 :  <p>&nbsp;</p>


   49 : {% endif %}


   50 : {% endblock %}

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
  307.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  79.         response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
  197.             return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
  28.             return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
  24.                 return func(self, *args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\db\transaction.py" in inner
  217.                 res = func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in change_view
  1030.         return self.render_change_form(request, context, change=True, obj=obj)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in render_change_form
  708.         ], context, context_instance=context_instance)
File "C:\Python27\lib\site-packages\django\shortcuts\__init__.py" in render_to_response
  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
  188.         return t.render(context_instance)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  123.             return self._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  117.         return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  117.         return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  117.         return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  117.         return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  117.         return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
  311.             return self.nodelist_true.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python27\lib\site-packages\sitetree\templatetags\sitetree.py" in render
  161.         tree_items = sitetree.tree(self.tree_alias, context)
File "C:\Python27\lib\site-packages\sitetree\sitetreeapp.py" in tree
  323.         tree_alias, sitetree_items = self.init_tree(tree_alias, context)
File "C:\Python27\lib\site-packages\sitetree\sitetreeapp.py" in init_tree
  235.         sitetree_items = self.get_sitetree(tree_alias)
File "C:\Python27\lib\site-packages\sitetree\sitetreeapp.py" in get_sitetree
  78.         self.get_tree_current_item(alias)
File "C:\Python27\lib\site-packages\sitetree\sitetreeapp.py" in get_tree_current_item
  140.                 current_url = urlquote(self.global_context['request'].path)
File "C:\Python27\lib\site-packages\django\template\context.py" in __getitem__
  60.         raise KeyError(key)

Exception Type: TemplateSyntaxError at /admin/sitetree/tree/1/
Exception Value: Caught KeyError while rendering: 'request'

It seems that it stems from the follwing function inside sitetreeapp.py:

def get_tree_current_item(self, tree_alias):
        """Resolves current tree item of 'tree_alias' tree matching current
        request path against URL of given tree item.

        """
        current_item = None

        if tree_alias in self.cache_current_item:
            current_item = self.cache_current_item[tree_alias]
        else:
            if 'request' not in self.global_context and self.global_context.current_app != 'admin':
                raise SiteTreeError('Sitetree needs "django.core.context_processors.request" template processor to be enabled. Please add it to TEMPLATE_CONTEXT_PROCESSORS in your settings file.')
            else:
                # urlquote is a try to support non-ascii in url.
                current_url = urlquote(self.global_context['request'].path) # request is missing here.
                if tree_alias in self.cache_urls:
                    for url_item in self.cache_urls[tree_alias]:
                        self.cache_urls[tree_alias][url_item][1].is_current = False
                        if self.cache_urls[tree_alias][url_item][0] == current_url:
                            current_item = self.cache_urls[tree_alias][url_item][1]

            self.cache_current_item[tree_alias] = current_item

        if current_item is not None:
            current_item.is_current = True

        return current_item

And in case you are wondering I do have django.core.context_processors.request in my TEMPLATE_CONTENT_PROCESSOR.

Can't make the documentation example work

Hi,

I am having problems to make it work like in the documentation.
Could you please help me? I'd really like to use django sitetree in my project.

Status:

  • urls generation and flagging the current branch and item is working ok
  • but the display of the tree menu or the breadcrumbs don't work with my tree.

I am using Django 1.4 named urls (format used in sitree_treeitem urls: my-url-name param.id).
I followed the explanations many times and I cannot find my error.

If my tree is:
Section 1
|---- Item B
|---- Item C
Section 2
|---- Item A
|---- Item D

When I am on the Section 1 page:

  • trunk is rendered (not ok) as the full tree:
    Section 1
    |---- Item B
    |---- Item C
    Section 2
    |---- Item A
    |---- Item D
  • this-children is rendered (ok) as:
    |---- Item B
    |---- Item C
  • this-ancestor-children is rendered (not ok) as:
    |---- Item B
    |---- Item C

Another breadcrumbs problem ))) 1.4

While we are thinking about userland breadcrumbs, there is an compatibility issue with breadcrumbs at contrib.admin (1.4).
Well, generally breadcrumb is not an issue, its a symptom.

the problem leads to NoReverseMatch error cuz in django they refactored internal url calling, now all urls in django apps are called by lazy url calling using url names and namespaces

so, to deal it, one should define "sitetree_treeitem_changelist" url name in def get_urls(self): at admin.py

so here are kinda fixes
https://github.com/vosi/django-sitetree/commit/14ec05910966a77bc6b169c00f7e455161feeb21
https://github.com/vosi/django-sitetree/commit/713125b3511610d56904a4df69371f1370592c86
https://github.com/vosi/django-sitetree/commit/196628e00148f29969c8b211b42d3eec0796dd1b
should work ok in 1.3
there is only one bug with breadcrumbs in history... dont know how to fix it

i understand that is sure not wery quality bug fix, but i think that best fix would be to totally refactor admin side, maybe using inlines (for trees) and popups (for adding/editing trees) should be more contrib.admin-ish... what do you say?

Bundle more basic menu templates

Consider bundling some more basic & fancy menu templates with the app and mention theirs availability in docs, with examples.

Export sitetree command needed

Export sitetree (for example to json) command would be fine for being able to reproduce tree structures quickly (see #28 for more info. nb: Russian inside).

Problem: Caught KeyError while rendering: 6L

Hello, Igor!

I have next menu:
root
--child1
--child2
--child3
--child4
--child5
root2

If I change parent in child3 on child1:
root
--child1
----child3
--child2
--child4
--child5
root2

I get error:
TemplateSyntaxError at /admin/sitetree/tree/4/
Caught KeyError while rendering: 6L

Request Method: GET
Request URL: http://localhost:8000/admin/sitetree/tree/4/
Django Version: 1.3.1
Exception Type: TemplateSyntaxError
Exception Value: Caught KeyError while rendering: 6L
Exception Location: /path/to/django_project/sitetree/sitetreeapp.py in get_item_by_id, line 141
Python Executable: /usr/bin/python2.7
Python Version: 2.7.1

Template error
In template /path/to/django_project/sitetree/templates/admin/sitetree/tree/change_form.html, error at line 46
Caught KeyError while rendering: 6L

I don't repeat this problem on another project, but I have sql-dump with this problem: http://dl.dropbox.com/u/13120653/sitetree_0.5_error.sql

I hope you may repair this bug,
Thank's!

Extending sitetree. Approaches

As it already mentioned in #38 from project to project there could be a need in extending sitetree items with custom attributes.
Decision wanted on approach to that matter.

Also mentioned in #43.

Error in admin tree view

fix "Caught AttributeError while rendering: 'NoneType' object has no attribute 'in_current_branch'"
maybe it is a dirty fix
https://github.com/vosi/django-sitetree/commit/2a1e51c0ed5a2b7a5a9aa53de66ed508d1064aad

also, consider merging
https://github.com/vosi/django-sitetree/commit/a99ee00070468b6930d8862bcbf43f9b77f1c2fc
https://github.com/vosi/django-sitetree/commit/4da17b9ea8bebd48b7a3105ca618e6e8b690fc87

it is a compatibility fix for 1.4, cuz this images are included in a single sprite

django 1.3

On trying to add a new sitetree I add the item and then when trying to edit it i get a

"django.template.base.TemplateSyntaxError

TemplateSyntaxError: Caught KeyError while rendering: 'request'
"

All the best!

Determining current item's ancestors for use in template

I'm trying to integrate sitetree into my site's layout and I'm looking for a nice way to check whether an item in sitetree is an ancestor for the currently selected item

Say you have a menu where part of it is structured like so:

Articles -> Category -> Entry

Now if you navigate to Entry (making it the current item) I'm looking for a way to check and tell in the template if 'Category' and 'Articles' are the "ancestors" to the current item so that I can alter the look/layout accordingly. An 'is_ancestor' flag on any items that are parent or parents of parents, etc. to the current item.

Forgive me if there is already a clean and easy way to determine it.

Add max_depth parameter

It would be good if you could specify the max_depth for the sitetree_menu template tag. This could be used e.g. when creating a top level menu that shouldn't display any of the subtrees.

A possible workaround is to create a custom template from which you remove the subtree processing loop. But a parameter in the tag would be cleaner.

I took a quick look at the sourcecode, and the way it's currently solved (counting arguments etc) it would be a hack to simply check for another argument with different if statements. A proper parser would be cleaner. I don't currently know much about parsers in Python, but I'll take a look at it, maybe I'll come up with a nice solution, if nobody beats me to it :)

Probably refs #46.

ru Бредкрамбы и свои урлы

Напишу по-русски, чтоб быстрей понять друг друга
Ситуация
дерево
/about/
*
/about/team/
**/about/history/
*/products/

урл продуктов обрабатывает другая аппа, естесно
урл продуктов может строится по разному (/products/category/_/, /products/type/_/, /products/item/***/), но начинается с /products/
задача, выводить бредкрамбы наполовину через сайттри
т.е. чтоб все то, с чем может разобраться сайттри выводилось сайттри, остальное - сам буду докидывать в темлейт
(link Products > link Category > Type)
в данный момент, если я на странице /products/something/ бредкрамба не выводится вообще, естественно
так как я не до конца вник в логику построения всех деревьев в аппе, сделал такой грязный хак https://github.com/vosi/django-sitetree/commit/6a6f7674010d6e535c8dfda05872d1f9c836d60c

вобщем, был бы благодарен, если б вы допилили этот функционал до красивого вида
и вообще, может нужно какой-то фреймворк для бредкрамбов сделать, чтоб можно было апендить бредкрамбы с любой апликухи
собственно, как и все дерево меню, в "виртуальные" ноды, которые не отображаются в меню, но показываются в крошках, полном древе

кстати, недоделка по менюхам, с целым плагин менегером (https://github.com/dhan88/django-treemenus)

Show for authenticated user

A more common case for me is showing navigational items based on whether or not the user is authenticated (for example, login and logout would be a use). I think that would be a great feature.

Make named URLs hint at tree item editor

Здравствуйте.
У django-extensions есть замечательная команда show_urls, которая делает следующее: Displays all of the url matching routes for the project.

Можно ли добавить в django-sitetree подсказки шаблонов URL-ов для облегчения набора урлов (автокомплит к примеру или ещё что-то).

Заранее спасибо.

modeltranslation and this app

Maybe you should include this hint in docs

using sitetree and modeltranslation

in some admin.py put this code

admin.site.unregister(Tree)
class TreeItemAdminNew(TreeItemAdmin, TranslationAdmin):
    class Media:
            js = ('admin/js/jquery-ui.min.js',
                  'modeltranslation/js/tabbed_translation_fields.js',)
            css = {'screen': ('modeltranslation/css/tabbed_translation_fields.css',),}

class TreeAdminNew(TreeAdmin):
    tree_admin = TreeItemAdminNew(TreeItem, admin.site)

admin.site.register(Tree, TreeAdminNew)

and register TreeItem in translation.py

SEO

Было бы полезно иметь возможность заинтегрировать django-sitetree с каким-нибудь django-seo, чтобы добавлять нужные мета-теги автоматически при создании дерева

Динамические Items в меню

Приветствую!
Мне в меню нужна иерархия вида:

  • Объекты
    ** Объект 1
    *** Аттрибуты <= current
    *** Связи
    ** Объект 2
    ** Объект 3
    Объект 1, 2, 3 - это объекты из БД. Атрибуты и связи - подпункты, которые есть у каждого объекта.
    В админке завел urlpattern вида /object/(?P<obj_id>\d+) и заголовок Объект {{obj.id}}. А как их туда подставить? Шаблон, который передаешь параметром в sitetree_menu верхний контекст не видит. Получается нужно как-то добавить айтемы объектов прямо в дерево?

management commands missing in pip package

I just did a pip install django-sitetree and the management folder seems to missing. I checked pip freeze and it says that sitetree is running 0.7. Has anyone else run into this issue?

Thanks,
Lloyd

Overriding the admin classes

I can't get the new admin functions override_tree_admin and override_item_admin to work. And I am not sure but don't they kinda violate the python explicit is better than implicit philosophy? Why not just do admin.site.unregister() and then register your custom admin that inherits from sitetree's?

For me that is what works right now. Although I can't seem to unregister the model TreeItem. Removing _reregister_tree_admin() at the end of sitetree/admin.py fixes the the problem.

Tree & TreeItem are coupled to SiteTree

I'm overriding the admin classes to change some default behavior. One thing i am doing is changing the name of the app by setting up proxy models for custom versions of Tree & TreeItem. The problem is that both the Tree & TreeItem classes are hardcoded into SiteTree. It would be great if we could pass our custom versions of Tree & TreeItem when instantiating SiteTree. This is done in the templatetag so I am not sure what the best approach would be. What is your take on this?

Error on multilanguage sites

With multilanguage site does not try to resolve tree_alias translation in menu, breadcrumbs and sitetree funcions

URL resolve

views:

from django.contrib.auth.views import password_reset_confirm

def account_password_confirm(request, uidb36, token):
    """
    Создание нового пароля
    """
    return password_reset_confirm(request,
        uidb36=uidb36,
        token=token,
        template_name='account/password_reset_confirm.html',
        post_reset_redirect=reverse('account_password_send'),
        extra_context= {'uidb36': uidb36, 'token': token}
    )

urls.py:

url(r'^password/reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'account_password_confirm', name='account_password_confirm'),

В админке для sitetree задаю url вида:
account_password_confirm uidb36 token
и получаю exception:

Unable to resolve title for current page using sitetree_page_title tag. Check whether there is an appropriate sitetree item defined for current URL.

Полный traceback: http://pastie.org/4000638

SiteTreeError

idlesign,

First, thanks for the great app.

When using django-registration with django-sitetree gives this error when completing a registration:

SiteTreeError: Sitetree needs "django.core.context_processors.request" to be in TEMPLATE_CONTEXT_PROCESSORS in your settings file. If it is, check that your view pushes request data into the template.

django.core.context_processors.request is present.

This works on the django development server, but does not work on an Apache server.

Full stack trace:

[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] mod_wsgi (pid=23655): Exception occurred processing WSGI script '/home/llc3e/django/projects/ischoolhub-staging/bin/django.wsgi'.
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] Traceback (most recent call last):
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/core/handlers/wsgi.py", line 241, in call
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] response = self.get_response(request)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/core/handlers/base.py", line 179, in get_response
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/core/handlers/base.py", line 228, in handle_uncaught_exception
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] return callback(request, *_param_dict)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/utils/decorators.py", line 91, in _wrapped_view
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] response = view_func(request, *args, *_kwargs)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/views/defaults.py", line 33, in server_error
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] return http.HttpResponseServerError(t.render(Context({})))
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/base.py", line 140, in render
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] return self._render(context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/base.py", line 134, in _render
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] return self.nodelist.render(context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/base.py", line 823, in render
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] bit = self.render_node(node, context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/base.py", line 837, in render_node
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] return node.render(context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/loader_tags.py", line 123, in render
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] return compiled_parent._render(context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/base.py", line 134, in _render
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] return self.nodelist.render(context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/base.py", line 823, in render
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] bit = self.render_node(node, context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/base.py", line 837, in render_node
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] return node.render(context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/loader_tags.py", line 62, in render
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] result = block.nodelist.render(context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/base.py", line 823, in render
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] bit = self.render_node(node, context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/.buildout/egg-cache/Django-1.4-py2.7.egg/django/template/base.py", line 837, in render_node
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] return node.render(context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/django/projects/ischoolhub-staging/parts/django-sitetree/sitetree/templatetags/sitetree.py", line 211, in render
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] tree_items = sitetree.menu(self.tree_alias, self.tree_branches, context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/django/projects/ischoolhub-staging/parts/django-sitetree/sitetree/sitetreeapp.py", line 369, in menu
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] tree_alias, sitetree_items = self.init_tree(tree_alias, context)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/django/projects/ischoolhub-staging/parts/django-sitetree/sitetree/sitetreeapp.py", line 350, in init_tree
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] sitetree_items = self.get_sitetree(tree_alias)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/django/projects/ischoolhub-staging/parts/django-sitetree/sitetree/sitetreeapp.py", line 208, in get_sitetree
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] self.get_tree_current_item(alias)
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] File "/home/llc3e/django/projects/ischoolhub-staging/parts/django-sitetree/sitetree/sitetreeapp.py", line 240, in get_tree_current_item
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] raise SiteTreeError('Sitetree needs "django.core.context_processors.request" to be in TEMPLATE_CONTEXT_PROCESSORS in your settings file. If it is, check that your view pushes request data into the template.')
[Thu Apr 19 12:05:47 2012] [error] [client 98.195.173.162] SiteTreeError: Sitetree needs "django.core.context_processors.request" to be in TEMPLATE_CONTEXT_PROCESSORS in your settings file. If it is, check that your view pushes request data into the template.

TagField does not update tags anymore

I believe it worked before but now I had to hack this though.
The post save signal isn't called anymore or was never called when submitting from a form like from the admin panel.
You should add to the TagField class the following method:

    def save_form_data(self, instance, data):
        Tag.objects.update_tags(instance, data)

After that everything works fine.
Currently I am just overriding the save_model in the ModelAdmin.

Exception при вложенных меню

Есть проблема:
Структура:
index.html:
{% sitetree_menu from "main_menu" include "trunk" template "sitetree/top_menu.html" %} -- главное меню
sitetree/top_menu.html:
{% sitetree_children of item for menu template "sitetree/top_child.html" %}
sitetree/top_child.html:
{% sitetree_menu from "main_menu" include "this-siblings" template "sitetree/secondlevel_menu.html" %}

На выходе получаем:
Caught SiteTreeError while rendering: Sitetree needs "django.core.context_processors.request" to be in TEMPLATE_CONTEXT_PROCESSORS in your settings file. If it is, check that your view pushes request data into the template.

Похоже, что при такой вложенности в последнее меню не проваливается контекст :(

django-registration: URL "registration_activate activation.key" fails

[ACTION]

Add site tree item with URL "registration_activate activation.key"

This maps to this urls.py entry from django-registration:

url(r'^activate/(?P<activation_key>\w+)/$',
activate,
name='registration_activate'),

[RESULT]

On request, the site tree item remains unresolved and sitetree_page_title call fails with error 500 due to current_item being None

[CAUSE]

Unknown

However "registration_activate " works for a particular activation key

For example:

URL: registration_activate e2d4b4b45901beef00fdf2a5c023da5b5fcc67ae

with "URL as a pattern" checked, works for:

http://127.0.0.1:8000/registration/activate/e2d4b4b45901beef00fdf2a5c023da5b5fcc67ae/

This can be done dynamically creating entries in sitetree but it's not practical

[RESOLUTION]

Unknown

Usage questions

Typical scenario: there are two menus (representing one tree), one on top (tab based, contains 1st level items), and sidemenu (contains 2nd and 3rd level items)

Tree structure looks like this:

  • Home
  • About
  • User
    • Change password
    • Messaging
      • Read messages
        • Latest
        • Unread
  • Legal

Top menu items:

  • Home
  • About
  • User
  • Legal

Side menu shows two levels starting from top menu. When any page in tree of "User" is selected, sidemenu should be:

  • Change password
  • Messaging
    • Read messages

Question: how do I show sidemenu?

Possible options are:

  1. using trunk -- problem is you don't know which branch of top menu is selected.
  2. using this-* -- problem is that "this" position changes depending on current page.

Is it possible to get something like current-active-branch-2nd-level-from-top and item.is_in_active_branch()

Thank you.

Cannot render individual menu items with sitetree_menu tag

I can't render individual items with this template tag. If I use "trunk" it works, but specifying sub-items by ID or alias does not work. I've tried individual items as well as plugging in all items in the tree as ids (e.g. "1,2,3").

Make the add treeitem button consistent

On change_form.html, instead of having just a link to the "Add tree item" page, use the standard Django add button. This is how do it in Grappelli:

{% block object-tools %}
{% if has_add_permission %}
    <ul class="tools">
        <li><a href="add/" class="add-handler focus">{% trans "Add tree item" %}</a></li>
    </ul>
{% endif %}
{% endblock %}

bugfix: for tree.html |yesno works in not right

Hello, Igor!

I found next bug and may give you bugfix (I think it's good): when I create tree elements I see access-icons, but they urls is not right generated :(.

Settings:
LANGUAGE_CODE = 'ru-RU'

We see in admin next url for icons:
/path/to/media/admin/icon-нет.gif

Problem in the "нет" because icons not found.

Versions:
Django: 1.3.1
Sitetree 0.5.1 (lastest github clone)
Locale by ru_RU

I create pull request with bugfix for this bug, please see #31

save() takes at most 3 arguments (4 given)

TypeError at /admin/sitetree/treeitem/add/
save() takes at most 3 arguments (4 given)
Request Method: POST
Request URL: http://192.168.1.10:8000/admin/sitetree/treeitem/add/
Exception Type: TypeError
Exception Value:
save() takes at most 3 arguments (4 given)
Exception Location: /usr/local/lib/python2.6/dist-packages/django_sitetree-0.1.0-py2.6.egg/sitetree/models.py in save, line 54
Python Executable: /usr/bin/python
Python Version: 2.6.5
Python Path: ['/home/graeme/Projects/ttmdjango', '/usr/local/lib/python2.6/dist-packages/mercurial-1.5.1-py2.6-linux-i686.egg', '/usr/local/lib/python2.6/dist-packages/django_siteblocks-0.1.0-py2.6.egg', '/usr/local/lib/python2.6/dist-packages/django_sitetree-0.1.0-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/pymodules/python2.6', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/local/lib/python2.6/dist-packages']
Server time: Sat, 12 Jun 2010 13:54:28 +0700

Menu generate by children as root.

Была бы крайне полезна возможность генерирования меню с указанием какое ответвление от древа использовать как корень. Например по указанию URL этого ответвления (title не подходит по причине использования многоязычности).
То есть чтобы не приходилось создавать новое древо для использования в шаблоне какой-то части существующего древа.
Например, это может выглядеть так:
{% sitetree_menu from "mytree" as_root "/about/" include "trunk,topmenu" %}

get_tree_current_item with i18n

get_tree_current_item не работает с i18n менюхами

при ините триапп и кешировании дерева в urls_cache кладется ключ tree_lang
а при обращении из темплейтов из urls_cache запрашивается просто tree
отказывается работать в бредкрамбах, в менюхах вроди как-то отрабатывает, хотя тоже - запрашивает get_tree_current_item

пришлось в def breadcrumbs (line ~444) добавить tree_alias = self.resolve_tree_i18_alias(tree_alias)
но думаю, там нужно править чуть глубже

Hidden elements show in sitetree_tree template

Hi, Igor!

We find bug with hidden element root: it's showing in tree-menu: {% sitetree_tree from "test_menu" %}.

Scheme:
root
--child1
--child2
--child3
--child4
--child5

Root-element showing but it hidden (checked all of checkbox: "Hidden", "Show in menu", "Show in breadcrumb path", "Show in site tree")...

Support for Sites contrib

Здравствуйте!
Попытался добавить поддержку мультисайтовости.

в models.py
class Tree(models.Model):
...
publish_on = models.ForeignKey(Site)
objects = models.Manager()
on_site = CurrentSiteManager('publish_on')

Теперь надо фильтровать вывод для сайта по SITE_ID, но где его установить, так и не разобрался.
.filter(publish_on=settings.SITE_ID)

По идее также надо модифицировать аlias на не уникальный, чтобы у каждого сайта была возможность использовать одинаковые алиасы (кэширование соответсвенно по primary_key, а не по alias делать) . Но для начала хотя бы просто сделать фильтрацию по SITE_ID.

Помогите пожалуйста.

Context in templates and global hook

Привет, Игорь.
Хочу тебя снова помучить вопросами ;)

  1. Почему в темплэйты, которые идут параметром в тэги sitetree_menu или sitetree_children, ты не передаешь весь родительский контекст? Передается только user и request, видно что это сделано намеренно, поэтому хотелось бы знать причину. Мне вот элементарно понадобился STATIC_URL для иконок меню, что я должен делать?

  2. Меня очень стремает передача хука через глобальную переменную. Может лучше ф-ию хкуа передавать через контекст, как callable или как строку с именем в крайнем случае? Так безопаснее, да и поведение становится более прозрачным и предсказуемым для разработчика, ИМХО.

Attribute error sitetree_menu icw (generic) ListView

When opening a generic view url, i get an attribute error:

AttributeError at /accounts/websites/list/
'QuerySet' object has no attribute 'split'
Request Method: GET
Request URL:    http://localhost:8000/accounts/websites/list/
Django Version: 1.4
Exception Type: AttributeError
Exception Value:    
'QuerySet' object has no attribute 'split'
Exception Location: /site/lib/python2.7/site-packages/sitetree/sitetreeapp.py in url, line 277

urls:
url(r'websites/list/$', WebsiteList.as_view(), name='website_list'),

view:

    class WebsiteList(ListView):
        model = Website
        context_object_name = "website_list"
        template_name = "websites/list.html"

        @method_decorator(login_required())
        def dispatch(self, *args, **kwargs):
            return super(WebsiteList, self).dispatch(*args, **kwargs)

        def get_queryset(self):
            return Website.objects.filter(user=self.request.user)

callstack:
File "/site/lib/python2.7/site-packages/sitetree/templatetags/sitetree.py" in render
211. tree_items = sitetree.menu(self.tree_alias, self.tree_branches, context)
File "/site/lib/python2.7/site-packages/sitetree/sitetreeapp.py" in menu
369. tree_alias, sitetree_items = self.init_tree(tree_alias, context)
File "/site/lib/python2.7/site-packages/sitetree/sitetreeapp.py" in init_tree
350. sitetree_items = self.get_sitetree(tree_alias)
File "/site/lib/python2.7/site-packages/sitetree/sitetreeapp.py" in get_sitetree
202. item.url_resolved = self.url(item)
File "/site/lib/python2.7/site-packages/sitetree/sitetreeapp.py" in url
277. view_path = resolved_var.split(' ')
    Exception Type: AttributeError at /accounts/websites/list/
Exception Value: 'QuerySet' object has no attribute 'split'

Introduce access right for sitetree items

It's often desirable to limit acces for certain parts of a webproject. Given that, sitretree might introduce a per item access limitation rules basing on Django rights system.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.