Started navigation refatoring
This commit is contained in:
@@ -1,9 +1,146 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
from django.template import (TemplateSyntaxError, Library,
|
||||
VariableDoesNotExist, Node, Variable)
|
||||
|
||||
from common.utils import urlquote
|
||||
|
||||
from .utils import (resolve_to_name, resolve_arguments,
|
||||
resolve_template_variable, get_navigation_objects)
|
||||
|
||||
object_navigation = {}
|
||||
multi_object_navigation = {}
|
||||
model_list_columns = {}
|
||||
sidebar_templates = {}
|
||||
top_menu_entries = []
|
||||
|
||||
link_binding = {}
|
||||
|
||||
|
||||
class ResolvedLink(object):
|
||||
active = False
|
||||
|
||||
|
||||
class Link(object):
|
||||
def __init__(self, text, view, args=None, kwargs=None, sprite=None, icon=None, permissions=None, condition=None):
|
||||
self.text = text
|
||||
self.view = view
|
||||
self.args = args or []
|
||||
self.kwargs = kwargs or {}
|
||||
self.sprite = sprite
|
||||
self.icon = icon
|
||||
self.permissions = permissions or []
|
||||
self.condition = condition
|
||||
|
||||
def resolve(self, context):
|
||||
request = Variable('request').resolve(context)
|
||||
current_path = request.META['PATH_INFO']
|
||||
current_view = resolve_to_name(current_path)
|
||||
|
||||
# Preserve unicode data in URL query
|
||||
previous_path = smart_unicode(urllib.unquote_plus(smart_str(request.get_full_path()) or smart_str(request.META.get('HTTP_REFERER', u'/'))))
|
||||
query_string = urlparse.urlparse(previous_path).query
|
||||
parsed_query_string = urlparse.parse_qs(query_string)
|
||||
|
||||
# Check to see if link has conditional display
|
||||
if self.condition:
|
||||
condition_result = self.condition(context)
|
||||
else:
|
||||
condition_result = True
|
||||
|
||||
if condition_result:
|
||||
#new_link = {}#copy.copy(link)
|
||||
resolved_link = ResolvedLink()
|
||||
try:
|
||||
args, kwargs = resolve_arguments(context, link.get('args', {}))
|
||||
except VariableDoesNotExist:
|
||||
args = []
|
||||
kwargs = {}
|
||||
|
||||
if 'view' in link:
|
||||
if not link.get('dont_mark_active', False):
|
||||
#new_link['active'] = link['view'] == current_view
|
||||
resolved_link.active = link['view'] == current_view
|
||||
|
||||
try:
|
||||
if kwargs:
|
||||
#new_link['url'] = reverse(link['view'], kwargs=kwargs)
|
||||
resolved_link.url = reverse(link['view'], kwargs=kwargs)
|
||||
else:
|
||||
# new_link['url'] = reverse(link['view'], args=args)
|
||||
resolved_link.url = reverse(link['view'], args=args)
|
||||
if link.get('keep_query', False):
|
||||
#print 'parsed_query_string', parsed_query_string
|
||||
#new_link['url'] = urlquote(new_link['url'], parsed_query_string)
|
||||
resolved_link.url = urlquote(new_link['url'], parsed_query_string)
|
||||
except NoReverseMatch, exc:
|
||||
#new_link['url'] = '#'
|
||||
resolved_link.url = '#'
|
||||
#new_link['error'] = err
|
||||
resolved_link.error = exc
|
||||
elif 'url' in link:
|
||||
if not link.get('dont_mark_active', False):
|
||||
#new_link['active'] = link['url'] == current_path
|
||||
resolved_link.url.active = link['url'] == current_path
|
||||
|
||||
if kwargs:
|
||||
#new_link['url'] = link['url'] % kwargs
|
||||
resolved_link.url = link['url'] % kwargs
|
||||
else:
|
||||
#new_link['url'] = link['url'] % args
|
||||
resolved_link.url = link['url'] % args
|
||||
if link.get('keep_query', False):
|
||||
#new_link['url'] = urlquote(new_link['url'], parsed_query_string)
|
||||
resolved_link.url = urlquote(new_link['url'], parsed_query_string)
|
||||
else:
|
||||
#new_link['active'] = False
|
||||
resolved_link.active = False
|
||||
|
||||
if 'conditional_highlight' in link:
|
||||
#new_link['active'] = link['conditional_highlight'](context)
|
||||
resolved_link.active = link['conditional_highlight'](context)
|
||||
|
||||
if 'conditional_disable' in link:
|
||||
#new_link['disabled'] = link['conditional_disable'](context)
|
||||
resolved_link.disabled = link['conditional_disable'](context)
|
||||
else:
|
||||
#new_link['disabled'] = False
|
||||
resolved_link.disabled = False
|
||||
|
||||
if current_view in link.get('children_views', []):
|
||||
#new_link['active'] = True
|
||||
resolved_link.active = True
|
||||
|
||||
#for child_url_regex in link.get('children_url_regex', []):
|
||||
# if re.compile(child_url_regex).match(current_path.lstrip('/')):
|
||||
# #new_link['active'] = True
|
||||
# resolved_link.active = True
|
||||
|
||||
#for children_view_regex in link.get('children_view_regex', []):
|
||||
# if re.compile(children_view_regex).match(current_view):
|
||||
# #new_link['active'] = True
|
||||
# resolved_link.active = True
|
||||
|
||||
for cls in link.get('children_classes', []):
|
||||
object_list = get_navigation_objects(context)
|
||||
if object_list:
|
||||
if type(object_list[0]['object']) == cls or object_list[0]['object'] == cls:
|
||||
#new_link['active'] = True
|
||||
resolved_link.active = True
|
||||
|
||||
return resolved_link
|
||||
#context_links.append(new_link)
|
||||
|
||||
|
||||
def bind_links(sources, links, menu_name=None):
|
||||
"""
|
||||
Associate a link to a model, a view, or an url
|
||||
"""
|
||||
link_binding.setdefault(menu_name, {})
|
||||
for source in sources:
|
||||
link_binding[menu_name].setdefault(source, {'links': []})
|
||||
link_binding[menu_name][source]['links'].extend(links)
|
||||
|
||||
|
||||
def register_multi_item_links(src, links, menu_name=None):
|
||||
"""
|
||||
@@ -21,29 +158,6 @@ def register_multi_item_links(src, links, menu_name=None):
|
||||
multi_object_navigation[menu_name][src]['links'].extend(links)
|
||||
|
||||
|
||||
def register_links(src, links, menu_name=None, position=None):
|
||||
"""
|
||||
Associate a link to a model a view, or an url
|
||||
"""
|
||||
|
||||
object_navigation.setdefault(menu_name, {})
|
||||
if hasattr(src, '__iter__'):
|
||||
for one_src in src:
|
||||
object_navigation[menu_name].setdefault(one_src, {'links': []})
|
||||
if position is not None:
|
||||
for link in reversed(links):
|
||||
object_navigation[menu_name][one_src]['links'].insert(position, link)
|
||||
else:
|
||||
object_navigation[menu_name][one_src]['links'].extend(links)
|
||||
else:
|
||||
object_navigation[menu_name].setdefault(src, {'links': []})
|
||||
if position is not None:
|
||||
for link in reversed(links):
|
||||
object_navigation[menu_name][src]['links'].insert(position, link)
|
||||
else:
|
||||
object_navigation[menu_name][src]['links'].extend(links)
|
||||
|
||||
|
||||
def register_top_menu(name, link, children_views=None,
|
||||
children_path_regex=None, children_view_regex=None,
|
||||
position=None):
|
||||
@@ -91,3 +205,56 @@ def register_sidebar_template(source_list, template_name):
|
||||
for source in source_list:
|
||||
sidebar_templates.setdefault(source, [])
|
||||
sidebar_templates[source].append(template_name)
|
||||
|
||||
|
||||
def get_object_navigation_links(context, menu_name=None, links_dict=object_navigation):
|
||||
request = Variable('request').resolve(context)
|
||||
current_path = request.META['PATH_INFO']
|
||||
current_view = resolve_to_name(current_path)
|
||||
context_links = []
|
||||
|
||||
# Don't fudge with the original global dictionary
|
||||
links_dict = links_dict.copy()
|
||||
|
||||
# Preserve unicode data in URL query
|
||||
previous_path = smart_unicode(urllib.unquote_plus(smart_str(request.get_full_path()) or smart_str(request.META.get('HTTP_REFERER', u'/'))))
|
||||
query_string = urlparse.urlparse(previous_path).query
|
||||
parsed_query_string = urlparse.parse_qs(query_string)
|
||||
|
||||
try:
|
||||
"""
|
||||
Override the navigation links dictionary with the provided
|
||||
link list
|
||||
"""
|
||||
navigation_object_links = Variable('overrided_object_links').resolve(context)
|
||||
if navigation_object_links:
|
||||
return [link for link in resolve_links(context, navigation_object_links, current_view, current_path, parsed_query_string)]
|
||||
except VariableDoesNotExist:
|
||||
pass
|
||||
|
||||
try:
|
||||
"""
|
||||
Check for and inject a temporary navigation dictionary
|
||||
"""
|
||||
temp_navigation_links = Variable('temporary_navigation_links').resolve(context)
|
||||
if temp_navigation_links:
|
||||
links_dict.update(temp_navigation_links)
|
||||
except VariableDoesNotExist:
|
||||
pass
|
||||
|
||||
try:
|
||||
links = links_dict[menu_name][current_view]['links']
|
||||
for link in resolve_links(context, links, current_view, current_path, parsed_query_string):
|
||||
context_links.append(link)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
for resolved_object in get_navigation_objects(context):
|
||||
try:
|
||||
links = links_dict[menu_name][type(resolved_object['object'])]['links']
|
||||
for link in resolve_links(context, links, current_view, current_path, parsed_query_string):
|
||||
context_links.append(link)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
return context_links
|
||||
|
||||
@@ -4,11 +4,11 @@ import copy
|
||||
import re
|
||||
import urlparse
|
||||
import urllib
|
||||
import logging
|
||||
|
||||
from django.core.urlresolvers import reverse, NoReverseMatch
|
||||
from django.template import (TemplateSyntaxError, Library,
|
||||
VariableDoesNotExist, Node, Variable)
|
||||
from django.utils.text import unescape_string_literal
|
||||
from django.utils.translation import ugettext as _
|
||||
from django.utils.encoding import smart_str, force_unicode, smart_unicode
|
||||
|
||||
@@ -17,9 +17,11 @@ from common.utils import urlquote
|
||||
from ..api import (object_navigation, multi_object_navigation,
|
||||
top_menu_entries, sidebar_templates)
|
||||
from ..forms import MultiItemForm
|
||||
from ..utils import resolve_to_name
|
||||
from ..utils import (resolve_to_name, resolve_arguments, resolve_template_variable,
|
||||
get_navigation_objects, get_object_navigation_links)
|
||||
|
||||
register = Library()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TopMenuNavigationNode(Node):
|
||||
@@ -51,28 +53,7 @@ class TopMenuNavigationNode(Node):
|
||||
def get_top_menu_links(parser, token):
|
||||
return TopMenuNavigationNode()
|
||||
|
||||
|
||||
def resolve_arguments(context, src_args):
|
||||
args = []
|
||||
kwargs = {}
|
||||
if type(src_args) == type([]):
|
||||
for i in src_args:
|
||||
val = resolve_template_variable(context, i)
|
||||
if val:
|
||||
args.append(val)
|
||||
elif type(src_args) == type({}):
|
||||
for key, value in src_args.items():
|
||||
val = resolve_template_variable(context, value)
|
||||
if val:
|
||||
kwargs[key] = val
|
||||
else:
|
||||
val = resolve_template_variable(context, src_args)
|
||||
if val:
|
||||
args.append(val)
|
||||
|
||||
return args, kwargs
|
||||
|
||||
|
||||
"""
|
||||
def resolve_links(context, links, current_view, current_path, parsed_query_string=None):
|
||||
"""
|
||||
Express a list of links from definition to final values
|
||||
@@ -141,92 +122,14 @@ def resolve_links(context, links, current_view, current_path, parsed_query_strin
|
||||
new_link['active'] = True
|
||||
|
||||
for cls in link.get('children_classes', []):
|
||||
obj, object_name = get_navigation_object(context)
|
||||
if type(obj) == cls or obj == cls:
|
||||
new_link['active'] = True
|
||||
object_list = get_navigation_objects(context)
|
||||
if object_list:
|
||||
if type(object_list[0]['object']) == cls or object_list[0]['object'] == cls:
|
||||
new_link['active'] = True
|
||||
|
||||
context_links.append(new_link)
|
||||
return context_links
|
||||
|
||||
|
||||
def get_navigation_object(context):
|
||||
try:
|
||||
object_name = Variable('navigation_object_name').resolve(context)
|
||||
except VariableDoesNotExist:
|
||||
object_name = 'object'
|
||||
|
||||
try:
|
||||
obj = Variable(object_name).resolve(context)
|
||||
except VariableDoesNotExist:
|
||||
obj = None
|
||||
|
||||
return obj, object_name
|
||||
|
||||
|
||||
def _get_object_navigation_links(context, menu_name=None, links_dict=object_navigation):
|
||||
request = Variable('request').resolve(context)
|
||||
current_path = request.META['PATH_INFO']
|
||||
current_view = resolve_to_name(current_path)
|
||||
context_links = []
|
||||
|
||||
# Don't fudge with the original global dictionary
|
||||
links_dict = links_dict.copy()
|
||||
|
||||
# Preserve unicode data in URL query
|
||||
previous_path = smart_unicode(urllib.unquote_plus(smart_str(request.get_full_path()) or smart_str(request.META.get('HTTP_REFERER', u'/'))))
|
||||
query_string = urlparse.urlparse(previous_path).query
|
||||
parsed_query_string = urlparse.parse_qs(query_string)
|
||||
|
||||
try:
|
||||
"""
|
||||
Override the navigation links dictionary with the provided
|
||||
link list
|
||||
"""
|
||||
navigation_object_links = Variable('overrided_object_links').resolve(context)
|
||||
if navigation_object_links:
|
||||
return [link for link in resolve_links(context, navigation_object_links, current_view, current_path, parsed_query_string)]
|
||||
except VariableDoesNotExist:
|
||||
pass
|
||||
|
||||
try:
|
||||
"""
|
||||
Check for and inject a temporary navigation dictionary
|
||||
"""
|
||||
temp_navigation_links = Variable('temporary_navigation_links').resolve(context)
|
||||
if temp_navigation_links:
|
||||
links_dict.update(temp_navigation_links)
|
||||
except VariableDoesNotExist:
|
||||
pass
|
||||
|
||||
try:
|
||||
links = links_dict[menu_name][current_view]['links']
|
||||
for link in resolve_links(context, links, current_view, current_path, parsed_query_string):
|
||||
context_links.append(link)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
obj, object_name = get_navigation_object(context)
|
||||
|
||||
try:
|
||||
links = links_dict[menu_name][type(obj)]['links']
|
||||
for link in resolve_links(context, links, current_view, current_path, parsed_query_string):
|
||||
context_links.append(link)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
return context_links
|
||||
|
||||
|
||||
def resolve_template_variable(context, name):
|
||||
try:
|
||||
return unescape_string_literal(name)
|
||||
except ValueError:
|
||||
#return Variable(name).resolve(context)
|
||||
#TODO: Research if should return always as a str
|
||||
return str(Variable(name).resolve(context))
|
||||
except TypeError:
|
||||
return name
|
||||
|
||||
"""
|
||||
|
||||
class GetNavigationLinks(Node):
|
||||
def __init__(self, menu_name=None, links_dict=object_navigation, var_name='object_navigation_links'):
|
||||
@@ -236,9 +139,10 @@ class GetNavigationLinks(Node):
|
||||
|
||||
def render(self, context):
|
||||
menu_name = resolve_template_variable(context, self.menu_name)
|
||||
context[self.var_name] = _get_object_navigation_links(context, menu_name, links_dict=self.links_dict)
|
||||
obj, object_name = get_navigation_object(context)
|
||||
context['navigation_object'] = obj
|
||||
context[self.var_name] = get_object_navigation_links(context, menu_name, links_dict=self.links_dict)
|
||||
object_list = get_navigation_objects(context)
|
||||
if object_list:
|
||||
context['navigation_object'] = object_list[0]['object']
|
||||
return ''
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,89 @@
|
||||
#http://www.djangosnippets.org/snippets/1378/
|
||||
from __future__ import absolute_import
|
||||
|
||||
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern, Resolver404, get_resolver
|
||||
|
||||
from django.template import (TemplateSyntaxError, Library,
|
||||
VariableDoesNotExist, Node, Variable)
|
||||
from django.utils.text import unescape_string_literal
|
||||
|
||||
__all__ = ('resolve_to_name',)
|
||||
#__all__ = ('resolve_to_name',)
|
||||
|
||||
def get_navigation_objects(context):
|
||||
object_list = []
|
||||
|
||||
# Try a simple 'object' search first, for lists templates
|
||||
try:
|
||||
resolved_object = Variable('object').resolve(context)
|
||||
except VariableDoesNotExist:
|
||||
try:
|
||||
object_name_list = Variable('navigation_object_list').resolve(context)
|
||||
except VariableDoesNotExist:
|
||||
try:
|
||||
object_name_list = [{'object': Variable('navigation_object_name').resolve(context)}]
|
||||
except VariableDoesNotExist:
|
||||
#try:
|
||||
# object_name_list = [{'object': Variable('list_object_variable_name').resolve(context)}]
|
||||
#except VariableDoesNotExist:
|
||||
return []
|
||||
#object_name_list = [{'object': 'object'}]
|
||||
#logger.debug('none found, falling back to "object"')
|
||||
#else:
|
||||
# logger.debug('found: list_object_variable_name')
|
||||
else:
|
||||
logger.debug('found: navigation_object_name')
|
||||
else:
|
||||
logger.debug('found: navigation_object_list')
|
||||
else:
|
||||
logger.debug('found single object')
|
||||
return [{'object': resolved_object}]#, 'object_name': 'object'}]
|
||||
|
||||
logger.debug('object_name_list: %s' % object_name_list)
|
||||
|
||||
for object_name in object_name_list:
|
||||
try:
|
||||
resolved_object = Variable(object_name['object']).resolve(context)
|
||||
except VariableDoesNotExist:
|
||||
resolved_object = None
|
||||
|
||||
object_list.append({'object': resolved_object})#, 'object_name': 'qwe'})
|
||||
|
||||
logger.debug('object_list: %s' % object_list)
|
||||
return object_list
|
||||
|
||||
|
||||
def resolve_template_variable(context, name):
|
||||
try:
|
||||
return unescape_string_literal(name)
|
||||
except ValueError:
|
||||
#return Variable(name).resolve(context)
|
||||
#TODO: Research if should return always as a str
|
||||
return str(Variable(name).resolve(context))
|
||||
except TypeError:
|
||||
return name
|
||||
|
||||
|
||||
def resolve_arguments(context, src_args):
|
||||
args = []
|
||||
kwargs = {}
|
||||
if type(src_args) == type([]):
|
||||
for i in src_args:
|
||||
val = resolve_template_variable(context, i)
|
||||
if val:
|
||||
args.append(val)
|
||||
elif type(src_args) == type({}):
|
||||
for key, value in src_args.items():
|
||||
val = resolve_template_variable(context, value)
|
||||
if val:
|
||||
kwargs[key] = val
|
||||
else:
|
||||
val = resolve_template_variable(context, src_args)
|
||||
if val:
|
||||
args.append(val)
|
||||
|
||||
return args, kwargs
|
||||
|
||||
|
||||
#http://www.djangosnippets.org/snippets/1378/
|
||||
def _pattern_resolve_to_name(self, path):
|
||||
match = self.regex.search(path)
|
||||
if match:
|
||||
@@ -40,6 +118,5 @@ def _resolver_resolve_to_name(self, path):
|
||||
RegexURLPattern.resolve_to_name = _pattern_resolve_to_name
|
||||
RegexURLResolver.resolve_to_name = _resolver_resolve_to_name
|
||||
|
||||
|
||||
def resolve_to_name(path, urlconf=None):
|
||||
return get_resolver(urlconf).resolve_to_name(path)
|
||||
|
||||
Reference in New Issue
Block a user