1 class MenuItem(object):
4 class InvalidMenuItem(BaseException):
7 def __init__(self, url, title, html_id=None, more_urls=None):
10 self.html_id = html_id
11 self.more_urls = more_urls or set()
16 def is_active(self, request, value):
17 url = request.get_full_path()
18 if url.startswith(str(self.url)):
20 for other_url in self.more_urls:
21 if url.startswith(str(other_url)):
25 def check_active(self, request, value):
27 self.active = self.is_active(request, value)
28 except self.InvalidMenuItem, e:
38 class ObjectMenuItem(MenuItem):
39 """Menu item corresponding to an object.
41 If no url or title is provided, get_absolute_url and __unicode__ are used.
42 You can also provide a reverse lookup dictionary, as in {model: field_name}.
45 obj=None, obj_get=None,
46 url=None, rev_lookups=None, title=None, html_id=None):
47 super(ObjectMenuItem, self).__init__(url=url, title=title, html_id=html_id)
49 self.obj_get = obj_get
50 self.rev_lookups = rev_lookups
54 return self.obj or self.obj_get()
55 except BaseException, e:
56 raise self.InvalidMenuItem(e)
59 return self.title or unicode(self.get_object())
62 return self.url or self.get_object().get_absolute_url()
66 obj = self.get_object()
67 except self.InvalidMenuItem, e:
71 def is_active(self, request, value):
72 if value == self.get_object():
75 for model, manager in self.rev_lookups.items():
76 if (isinstance(value, model) and
77 self.get_object() in getattr(value, manager).all()):
82 class ModelMenuItem(MenuItem):
83 """Menu item corresponding to a model, optionally filtered by some fields."""
85 def __init__(self, model, url, field_lookups=None, title=None, html_id=None):
87 title = unicode(model)
88 super(ModelMenuItem, self).__init__(title=title, url=url, html_id=html_id)
90 self.field_lookups = field_lookups
92 def is_active(self, request, value):
93 if value == self.model and not self.field_lookups:
95 if str(self.url) == request.get_full_path():
97 if isinstance(value, self.model) and self.field_lookups:
99 for field, lookup in self.field_lookups.items():
100 if getattr(value, field) != lookup:
107 return self.title or unicode(self.model)