Question

I have an admin mixin that I'm using to prevent caching and make sure users are logged in by overriding dispatch(). It's being used in my class-based views.

# mixins.py
from django.contrib.admin.views.decorators import staff_member_required
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache

class AdminPageMixin(object):
    @method_decorator(never_cache)
    @method_decorator(staff_member_required)
    def dispatch(self, request, *args, **kwargs):
        return super(AdminPageMixin, self).dispatch(request, *args, **kwargs)

# views.py
class SomeAdminView(AdminPageMixin, ListView):

I'm running into a problem when I'm trying to run unit tests against SomeAdminView. Yes, I know I can use django's test client to login, but I'm trying to stay away from writing functional tests. I'd like, instead, to wrap AdminPageMixin functionality into a single decorator and call that decorator in urls.py, like so:

url(r'^myurl/$', decorator_wrapper(SomeAdminView.as_view()), name='some-admin-view'),

Alternatively, I could do this:

url(r'^myurl/$', never_cache(staff_member_required(SomeAdminView.as_view())), name='some-admin-view'),

but if I wanted to add a third or forth decorator, I'd be updating a lot of lines in urls.py and repeating a lot of code.

Any ideas how to create this decorator wrapper?

Était-ce utile?

La solution

It is quite against the spirit of the CBVs to use decorators in the URLconfs. Instead, use mixins to add the functionality directly to the dispatch method of the view class.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top