はじめに
ユーザーの作成
- 前回の環境構築でユーザーを作成していなかったので、ユーザーを作成しておく。
- メールアドレスとユーザー名は変えて下さい。
python manage.py createsuperuser --email admin@example.com --username admin
REST Framework の設定
プロジェクトで作成した方のディレクトの設定
- /backend/backend/settings.py に API アプリケーションを追加する。
INSTALLED_APPS = [
### 作成したAPIアプリケーション
'api.apps.ApiConfig',
# 3rd party
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
- backend/backend/urls.pyにアプリケーションにアクセスするためのURLを設定する
from django.contrib import admin
## includeを追加する
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
## 作成したAPIアプリケーションのパスを設定する
path('api/', include('api.urls')),
]
アプリケーション側の設定
- /backend/api/ファイルに「urls.py」ファイルを作成する
from . import views
from django.urls import include, path
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
path('test/', views.index, name='index'),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
- /backend/api/ファイルに「serializers.py」ファイルを作成する
- 下記の記述はREST Frameworkのチュートリアルと同じ
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
- /backend/api/ファイルに「views.py」ファイルを編集する
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from api.serializers import UserSerializer, GroupSerializer
## お約束のHello world! をHTMLで出力する
def index(request):
return HttpResponse("Hello, world!!")
### REST frameworkのチュートリアルと同じ記述
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
実行結果