Shared/Global Dictionary in Django Between URLs an

2019-07-24 18:02发布

At runtime I'm trying to generate a tree of parent-child relationships between views using the urls.py of different apps. I'm trying to accomplish breadcrumbs by allowing this tree to be defined by an extension of the url function that accepts extra arguments for view_name (name to display on page when used on page, like "Home") and parent_view (specifies the immediate parent so you can generate your breadcrumb).

This class is defined in a separate file in its own module utils.breadcrumbs. The class is called BreadCrumbs and I try to define an instance of BreadCrumbs in the same file for import into various files. This is where it breaks I think.

utils/breadcrumbs.py

class BreadCrumbs:
    breadcrumbs = {} # This is our tree
    def url(self, pattern, view, arguments={}, name=None, view_name=None, parent_view=None):
        ... Adds node to self.breadcrumbs ...
        return url(pattern, view, arguments, name)

bc = BreadCrumbs()

app/urls.py

from utils.breadcrumbs import bc
urlpatterns = patterns('',
    bc.url(r'^home/$', 'app.views.home', name='home', view_name='Home'),
    bc.url(r'^subpage/$', 'app.views.subpage', view_name='Sub Page', parent_view="app.views.home"),
)

Then I try to access the tree defined in breadcrumbs.bc in a context processor using the view name given through a middleware. When I had all of my url patterns in the core urls.py file instead of in separate apps, it worked fine. Now that I've moved the url patterns to separate files, the tree is empty when I go to call it in my context processor using a from utils.breadcrumbs import bc. Am I using global variables incorrectly here? Is there a more correct method to share a variable between my urls.py and my context processor? I've looked at sessions, but I don't have access to the request in urls.py, correct?

Your help is appreciated in advance.

0条回答
登录 后发表回答