DEV Community

k11o for Takenoko Tech LLC.

Posted on

3 2

DjangoのClass-Based Viewで権限確認を行う

DjangoでClass-Based ViewによるDetailView等を実装している際に、そのViewへのアクセスの可否をカスタムで確認したい場合があると思います。
例えば下記の様なモデルのDetailViewにおいて、各ユーザー自分のデータしか見れないようにする、などと言った場面です。

class Memo(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
Enter fullscreen mode Exit fullscreen mode
path('memo/<int:pk>', views.MemoDetailView.as_view(),
         name='memo_detail'),
Enter fullscreen mode Exit fullscreen mode
class MemoDetailView(DetailView):
    model = models.Memo
Enter fullscreen mode Exit fullscreen mode

このままだと memo/2 のような適当な URL を入れることで誰でも閲覧可能になってしまいます。これを自分の Memo しか見れないようにします。

このような場面のためにテスト用のclassが用意されています。

test_func で OK/NG を Bool で返せば良いので、今回の場合だと下記のようなclassを作成し

class ObjectOwnerCheckMixin(UserPassesTestMixin):
    def test_func(self):
        login_user = self.request.user
        object_owner = self.get_object().user
        return login_user == object_owner
Enter fullscreen mode Exit fullscreen mode

View側ではそれを継承すればOKです。

class MemoDetailView(ObjectOwnerCheckMixin,DetailView):
    model = models.Memo
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay