On 24 March 2011 15:32, Ian Stokes-Rees <ijsto...@hkl.hms.harvard.edu> wrote:
> I think with the move to class-based Generic Views it is necessary to update
> this documentation:
>
> Limiting access to generic views
>
> To limit access to a generic view, write a thin wrapper around the view, and
> point your URLconf to your wrapper instead of the generic view itself. For
> example:
>
> from django.views.generic.date_based import object_detail
>
> @login_required
> def limited_object_detail(*args, **kwargs):
>     return object_detail(*args, **kwargs)

Yeah, that probably needs an update. The topic guide on Class-based
Generic views has the right examples[1]:

### In URLconf, you can do:

from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView

urlpatterns = patterns('',
    
(r'^about/',login_required(TemplateView.as_view(template_name="secret.html"))),
)

### Decorating class:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

class ProtectedView(TemplateView):
    template_name = 'secret.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ProtectedView, self).dispatch(*args, **kwargs)

---

You can also decorate as_view(), like you tried to:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import classonlymethod
from django.views.generic import TemplateView

class ProtectedView(TemplateView):

    @classonlymethod
    def as_view(cls, **initargs):
        return login_required(super(ProtectedView, cls).as_view(**initargs))

This can be further abstracted into view_decorator() function[2].


[1]: 
http://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-the-class
[2]: 
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-users@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