django-simple-menu
django-simple-menu copied to clipboard
add current View's name to MenuItem's attrs
Despite I shouldn't write this ;-), I think it may be of help in django-simple-menu.
I've tried many menu systems, and all are flawed with issues that render them unusable for bigger projects. DSM ist great, really, just lacks some features that are urgently needed in projects with "special needs", like those using django-hosts.
When using django-hosts, using dynamic hosts (stored in database and checked vie middleware against current domain) with django-simple-menu, you run into a problem that is not easy to solve. When you e.g. have a host, whose urls.py has no /admin/
path, and another host, which has path(/admin/
,...) AND a MenuItem with a url named reverse(admin:index)
, you get an Exception when opening the first host's site: as generate_menu
runs through ALL MenuItems (of all hosts), but the urls.py doesn't contain a /admin
path, the reverse(admin:index)
points to a non-existing URL. Bang.
I struggled many days with this issue, and finally came up with a solution: using reverse_lazy
instead of reverse
and subclassing MenuItem + adding code to get the current View's name, I can determine which menu items are visible on that domain.
This solution is not specific to django-hosts - in fact - it has nothing to do with hosts at all, it is generic: If you add view_name
as property to MenuItem, and add some logic that it is invisible when the current view is not the one specified in view_name
, everything is fine.
So I would propose a newattr to MenuItem: view_name
:
def __init__(self, ..., view_name="",...):
#...
self.view_name = view_name
#...
def process(self, request: HttpRequest):
if self.view_name:
self.visible = request.resolver_match.view_name == self.view_name
if not self.visible:
return
super().process(request)
Please tell me what you think about that.