他にも、認証が必要なすべてのビューでログインデコレータを使用する必要があることが指摘されている人もいます。
あなたは、単にこのようにそれをラップすることにより、それを再使用することができます。
auth = login_required(login_url='/accounts/login/')
@auth
def index(request):
return render(request, 'post.html', {})
@auth
def new(request):
return render(request, 'post-add.html',)
をそれとも、クラスベースのビューを好きなら、私は好むこの:
class AuthMixin(object):
@method_decorator(login_required(login_url='/accounts/login/'))
def dispatch(self, *args, **kwargs):
return super(AuthMixin, self).dispatch(*args, **kwargs)
class IndexView(AuthMixin, TemplateView):
template_name = 'post.html'
class AddView(AuthMixin, TemplateView):
template_name = 'post-add.html'
はそれを少し簡単にするために、 mixinをTemplateViewから継承させ、すべてのログインに必要なビューに対して単一の基本クラスとして使用することができます。
どちらの方法でも、設定からログインURLを取得することをお勧めします。
すべてのビューでログインURLを文字列として指定することはお勧めできません。特にデフォルトのdjango設定になっている場合は、 – Sayse