From 584044566414d3f4595337225aa23b52a089a680 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Mon, 17 Mar 2014 06:49:59 -0400 Subject: [PATCH] Fixed #22006 -- Documented how to write a login_required mixin for CBVs. Thanks django at patjack.co.uk for the suggestion and mockforest for the draft patch. --- docs/topics/auth/default.txt | 6 ++++-- docs/topics/class-based-views/intro.txt | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/docs/topics/auth/default.txt b/docs/topics/auth/default.txt index 5d93e432a4..15c895f0aa 100644 --- a/docs/topics/auth/default.txt +++ b/docs/topics/auth/default.txt @@ -564,14 +564,16 @@ The permission_required decorator The :func:`~django.contrib.auth.decorators.permission_required` decorator can take a list of permissions as well as a single permission. +.. _applying-permissions-to-generic-views: + Applying permissions to generic views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To apply a permission to a :doc:`class-based generic view `, decorate the :meth:`View.dispatch ` method on the class. See -:ref:`decorating-class-based-views` for details. - +:ref:`decorating-class-based-views` for details. Another approach is to +:ref:`write a mixin that wraps as_view() `. .. _built-in-auth-views: diff --git a/docs/topics/class-based-views/intro.txt b/docs/topics/class-based-views/intro.txt index 906205b96c..c307fc603d 100644 --- a/docs/topics/class-based-views/intro.txt +++ b/docs/topics/class-based-views/intro.txt @@ -173,6 +173,29 @@ that inherits from ``View`` - for example, trying to use a form at the top of a list and combining :class:`~django.views.generic.edit.ProcessFormView` and :class:`~django.views.generic.list.ListView` - won't work as expected. +.. _mixins_that_wrap_as_view: + +Mixins that wrap ``as_view()`` +------------------------------ + +One way to apply common behavior to many classes is to write a mixin that wraps +the :meth:`~django.views.generic.base.View.as_view()` method. + +For example, if you have many generic views that should be decorated with +:func:`~django.contrib.auth.decorators.login_required` you could implement a +mixin like this:: + + from django.contrib.auth.decorators import login_required + + class LoginRequiredMixin(object): + @classmethod + def as_view(cls): + return login_required(super(LoginRequiredMixin, cls).as_view()) + + class MyView(LoginRequiredMixin, ...): + # this is a generic view + ... + Handling forms with class-based views =====================================