Djangoのアプリに管理画面の認証を流用する

認証機能を実装する際に、ユーザ管理やログイン画面などを作るのが面倒というあなた!管理画面のアカウントやグループの管理や、ログイン画面を流用しちゃう方法を試してみたので参考までご活用下さい。

目次

前提

  1. 基本となるDjangoの環境はこちらで作成したものを利用します
  2. アプリはクラスベースViewとしていますが、関数ベースでもアノテーションを使う程度で大きくは変わりません
  3. アプリのパスは /testapp/myview とします
    • 先の環境で作成したHostの一覧を表示させます
  4. 管理画面のログインログアウトのパスは固定で以下の通りです
    • ログイン画面  /accounts/login/
    • ログアウト画面 /accounts/logout/
  5. 各コードのパスはコンテナ内の場所で記載しています

urls.pyの設定

プロジェクト側の設定

/code/testprj/urls.py

from django.contrib import admin
from django.urls import path, include

# auth
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testapp/', include('testapp.urls', namespace='restapi')),
    path('accounts/login/', auth_views.LoginView.as_view(), name='login'),
    path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
]

アプリ側の設定

/code/testapp/urls.py

from django.urls import path, include
from .views import *

app_name = 'testapp'
urlpatterns = [
    path('myview/', MyView.as_view(), name='myview'),
]

これで、 /testapp/myview でアクセスするとmyviewクラスのviewクラスが呼び出されるようになります。

アプリのviews.pyの設定

/code/testapp/views.py

from django.shortcuts import render
from .models import *
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, ListView

class MyView(LoginRequiredMixin, ListView):
    model = Host
    template_name = '/code/testapp/templates/testapp/my_templates.html'

アプリのテンプレート設定

見た目のスタイルも本来は自前で用意しないといけないんだけど、ココも管理画面のスタイルを流用するように、admin/base.html を extends しちゃいます。

/code/testapp/templates/testapp/my_templates.html

{% extends "admin/base.html" %}
{% block content %}

<table>
    <thead>
        <tr>
            <th scope="col">ID</th>
            <th scope="col">Host</th>
            <th scope="col">SerialNo</th>
            <th scope="col">type</th>
        </tr>
    </thead>
    <tbody>
    {% for line in object_list %}
        <tr>
            <th> {{ line.id }}  </th>
            <td> {{ line.name }} </td>
            <td> {{ line.sn }}  </td>
            <td> {{ line.type_id }} </td>
        </tr>
    {% endfor %}
    </tbody>
</table>

{% endblock %}

その他

アカウントを流用する場合、すべてのアカウントが /admin の管理画面に入られるnのは困るといった場合があると思いますが、そのあたりはGroupを用いて管理画面に入れるアカウントとそうでないアカウントを管理すると良いです。


投稿日

カテゴリー:

投稿者: