djangoのアクセス制限に関してです。
ログインしているユーザーのみ
といったアクセス制限の方法は日本語資料でも確認できましたが、
superuser
のみといったアクセス制限の方法については、あまり見かけなかったので解説します。
誰かの役に立てば、幸いです。
環境
- Django 2.2.4
関数で開発している場合
デコレータをつけることでいけます。
views.py
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse
@permission_required('admin.can_add_log_entry')
def test(request):
return HttpResponse("Only access superuser!")
classで開発している場合
せっかく、djangoを使っているなら、classベースで開発したいですよね。
そんな時のためのTips。
1. mixins.pyを定義
djangoのアプリ内で、mixins.py
を作成します。
mixins.py
from django.contrib.auth.mixins import UserPassesTestMixin
class SuperuserRequiredMixin(UserPassesTestMixin):
def test_func(self):
return self.request.user.is_superuser
2.views.pyで継承
ここで、定義したclassをviews.pyで使用します。
views.py
from .mixins import SuperuserRequiredMixin
class TestView(SuperuserRequiredMixin,TemplateView):
template_name = "test/home.html"
こんな感じになるはず。
参考になったら、幸いです。