1
3

More than 3 years have passed since last update.

Djangoでsuperuserのみでアクセス制限を行う方法

Last updated at Posted at 2021-08-06

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"

アクセス制限ができれば、
キャプチャ.PNG

こんな感じになるはず。

参考になったら、幸いです。

参考文献

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3