Moved from django-developers:

On 7 December 2010 20:15, Sean Brant <brant.s...@gmail.com> wrote:
> Again this topic is now in django-user land.
>
> I do this in views.py if want the decorator on all methods (get|post).
>
> myview = login_required(MyView.as_view())
>
>
>
> On Dec 7, 2010, at 1:10 PM, Daniel Swarbrick <daniel.swarbr...@gmail.com> 
> wrote:
>
>> That is indeed in the docs, and I have seen that. What eludes me is
>> how to use decorators more complex than login_required() from within
>> urls.py.
>>
>> For example, this works fine:
>>
>> from django.contrib.auth.decorators import user_passes_test
>> from django.utils.decorators import method_decorator
>> from django.views.generic import TemplateView, View
>>
>> class IndexView(TemplateView):
>>    template_name = 'index.html'
>>
>>   �...@method_decorator(user_passes_test(lambda u: u.is_superuser))
>>    def dispatch(self, *args, **kwargs):
>>        return super(IndexView, self).dispatch(*args, **kwargs)
>>
>> But how would one avoid having to override the dispatch() method on
>> many classes, and put the user_passes_test() decorator in the urls.py
>> definition? Or for that matter, the permission_required() decorator?

One option is to make a base class that has the right method decorated
and then subclass it. This is what the docs show. Another is to
decorate the function returned by as_view().

>>
>> As a side note, could a mixin be used to setup permission_required,
>> login_required etc, and user-defined class-based views be derived from
>> multiple parent classes?

Yes. Some decorators make sense as Mixins, others don't - it's a
matter of judgement. IMHO, login_required doesn't make much sense as a
Mixin.

>>
>> Sorry if this has meandered into django-users land... maybe some
>> advanced CBV examples in the docs?

Here's a view from my project:

@view_decorator(never_cache)
@view_decorator(csrf_exempt)
@view_decorator(domain_required(login=True))
class FileCollectionView(JSONMixin, PersonMixin, SingleObjectMixin, View):
   # lots of secret code :)
   pass

This uses view_decorator() function I wrote[1], which is a shortcut
for overriding ``as_view`` method (I prefer to override that instead
of ``dispatch``). Maybe you'll find it helpful.

[1]: 
https://github.com/lqc/django/blob/0eb2de3c156d8e6d1c31f46e0734af0ff06f93c4/django/utils/decorators.py#L46


-- 
Łukasz Rekucki

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to