How to override `as_view` in classes in Django?

I am trying to present class based representations in my project. So far, it was good until I found the following problem.

I use django-navigationto create breadcrumbs. It works as follows: the view function gets the look, and this decorator introduces an attribute of this function called breadcrumb. In the template, the current URL or part of it will be resolved, and the result will be a check of this attribute. If he is there, he is evaluated, and the result is the text of the palette.

Since class-based representations are usually represented by a method as_view(), it seems to me that I will need to decorate it, however, since this is a class method, I can not access the instance there, which, of course, depends on.

Attaching an attribute breadcrumbto as_view()in __init__()does not work either, or I received the syntax incorrectly. EDIT . Of course, this did not work, since I bound it to as_view, and not to its return value.

Any ideas on how to properly integrate this color palette decorator and class-based views?

+5
source share
2 answers

I solved it now. I put my routine breadcrumbin a method on a child class and redefined as_viewin my base view. The actual trick is also used as_viewto get the pointer self.

@classonlymethod
def as_view(cls, **initkwargs):
    self = cls(**initkwargs)
    view = super(MyBaseView, cls).as_view(**initkwargs)
    if hasattr(self, 'breadcrumb') and callable(getattr(self, 'breadcrumb', None)):
        return breadcrumb(self.breadcrumb)(view)
    return view
+8
source

, - urls.py:

the_view = ListView.as_view(...)
the_view = the_decroator(the_view)

urlpatterns = patterns('',
    url(r'^$', the_view, name='app_index'),
    ...
)

as_view , . "@" - , 2.

+1

All Articles