django-admin startapp postings
후 setting에 앱 연결
# postings/models.py
from django.db import models
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Post(TimeStampedModel):
post_title = models.CharField(max_length=100)
post_content = models.CharField(max_length=500)
image_url = models.CharField(max_length=200)
user = models.ForeignKey('users.User', related_name='posts', on_delete=models.CASCADE)
class Meta:
db_table = "postings"
# config/urls.py
from django.urls import path, include
urlpatterns = [
path("users", include('users.urls')),
path("postings", include('postings.urls')),
]
# postings/urls.py
from django.urls import path
from .views import PostingView
urlpatterns = [
path("upload", PostingView.as_view())
]
# postings/views
import json, jwt
from django.views import View
from django.http import JsonResponse
from .models import Post
from secret import ALGORITHM
from config.settings import SECRET_KEY
class PostingView(View):
def post(self, request):
try:
data = json.loads(request.body)
post_title = data["post_title"]
post_content = data["post_content"]
payload = jwt.decode(data["token"], SECRET_KEY, ALGORITHM)
Post.objects.create(
post_title = post_title,
post_content = post_content,
image_url = data["image_url"],
user_id = payload['user_id'],
)
return JsonResponse({"MESSAGE": "Post created!"}, status=201)
except KeyError:
return JsonResponse({"MESSAGE": "KEY_ERROR"}, status=400)
posting을 생성하기 위해선 post_title, post_content, image_url, user_id가 필요합니다. 이 때 user는 인가된 인원이어야 하므로 토큰을 decode한 user_id가 user_id와 같으면 생성하도록 합니다.
class PostingView(View):
.
.
.
def get(self, request):
posts = Post.objects.all()
results = []
for post in posts:
results.append(
{
"id" : post.id,
"post_title" : post.post_title,
"post_content" : post.post_content,
"image" : post.image_url,
"user_id" : post.user_id,
"user" : {
"id" : post.user.id,
"first_name" : post.user.first_name,
"last_name" : post.user.last_name,
"email" : post.user.email,
"phone_number" : post.user.phone_number,
}
}
)
return JsonResponse({"postings" : results}, status = 200)
작성된 posts를 가져옵니다. 그리고 for문을 돌려 하나씩 post에 대한 정보들을 집어넣습니다. 그 정보들을 results에 넣고 마지막에 results를 리턴합니다.
user의 정보를 가져올 때는 post.user.가져올_정보
로 가져옵니다. post는 user와 외래키로 연결되어 있고 정참조를 하고 있습니다.(post: 다, user: 일)
포스트맨으로 포스팅 하기!!
짜잔~