Warning: count(): Parameter must be an array or an object that implements Countable in /home/xs638785/agile-software.site/public_html/wp-content/plugins/rich-table-of-content/functions.php on line 490
仮想環境
python3 -m venv myvenv
source myvenv/bin/activate
requirements.txt
Django~=3.1.4
django-cors-headers==3.4.0
djangorestframework==3.11.1
djangorestframework-simplejwt==4.6.0
djoser==2.0.3
python-decouple
dj-database-url
dj-static
プロジェクト作成
django-admin startproject rest_api .
アプリ作成
django-admin startapp api
settings.py
from datetime import timedelta
from decouple import config
from dj_database_url import parse as dburl
INSTALLED_APPS = [
'rest_framework',
'api.apps.ApiConfig',
'corsheaders',
'djoser',
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
CORS_ORIGIN_WHITELIST = [
"http://localhost:3000", "https://nextjs-blog-todos.vercel.app"
]
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('JWT',),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
}
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
# Database
default_dburl = 'sqlite:///' + str(BASE_DIR / "db.sqlite3")
DATABASES = {
'default': config('DATABASE_URL', default=default_dburl, cast=dburl),
}
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = str(BASE_DIR / 'staticfiles')
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.CharField(max_length=500)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id) + " - " + self.title
Serializerのcreateをそのまま使ってしまうとパスワードが暗号化されずにデータベースに保存されてしまう。
created_atの形式を変更します。何年何月何日何時何分何秒。
created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
views.py
ブログの投稿データの一覧を取得
from rest_framework.permissions import AllowAny
from rest_framework import generics
from rest_framework import viewsets
from .serializers import UserSerializer, Content_proSerializer
from .models import Content_pro
class CreateUserView(generics.CreateAPIView):
serializer_class = UserSerializer
permission_classes = (AllowAny,)
class Content_proListView(generics.ListAPIView):
queryset = Content_pro.objects.all()
serializer_class = Content_proSerializer
permission_classes = (AllowAny,)
class Content_proRetrieveView(generics.RetrieveAPIView):
queryset = Content_pro.objects.all()
serializer_class = Content_proSerializer
permission_classes = (AllowAny,)
views.py
管理
python manage.py createsuperuser