对于 Django 1.9 或更高版本;基于类的视图 (CBV) 可以利用 auth 包中的 mixin。只需使用以下语句导入 -
from django.contrib.auth.mixins import LoginRequiredMixin
mixin 是一种特殊的多重继承。使用mixin主要有两种情况:
- 您想为一个类提供许多可选功能。
- 您想在许多不同的类中使用一个特定的功能。
了解更多:What is a mixin, and why are they useful?
CBV 使用 login_required 装饰器
urls.py
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from .views import ListSecretCodes
urlpatterns = [
url(r'^secret/$', login_required(ListSecretCodes.as_view()), name='secret'),
]
views.py
from vanilla import ListView
class ListSecretCodes(LoginRequiredMixin, ListView):
model = SecretCode
CBV 使用 LoginRequiredMixin
urls.py
from django.conf.urls import url
from .views import ListSecretCodes
urlpatterns = [
url(r'^secret/$', ListSecretCodes.as_view(), name='secret'),
]
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from vanilla import ListView
class ListSecretCodes(LoginRequiredMixin, ListView):
model = SecretCode
注意
以上示例代码使用django-vanilla 轻松创建基于类的视图(CBV)。使用 Django 的内置 CBV 和一些额外的代码行也可以达到同样的效果。