게시물 등록 클래스를 생성해주세요.
게시물을 등록할 때에는 post
메소드를 사용합니다.
게시물 생성 시간은 등록하는 현재 시간이어야 합니다.
python manage.py startapp posting
INSTALLED_APPS에 새로 만든 앱 'posting' 추가
from django.db import models
from user.models import User
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
image_url = models.URLField(max_length=2000)
content = models.TextField(null=True)
class Meta:
db_table = 'posts'
PostView 클래스 작성
import json
from django.http import JsonResponse
from django.views import View
from user.models import User
from .models import Post
class PostView(View):
def post(self, request):
try:
data = json.loads(request.body)
email = data['email']
image_url = data['image_url']
content = data['content']
if not User.objects.filter(email=email).exists():
return JsonResponse({'message': 'INVALID_USER'}, status=401)
user = User.objects.get(email=email)
Post.objects.create(user=user, image_url=image_url, content=content)
return JsonResponse({'message': 'SUCCESS'}, status=200)
except KeyError:
return JsonResponse({'message': 'KEY_ERROR'}, status=400)
등록된 모든 게시물을 나열하는 게시물 표출 클래스를 생성해주세요.
게시물을 나타낼 때에는 get
메소드를 사용합니다.
게시물을 나타낼 때에는 등록한 사람, 게시물, 게시된 내용, 게시된 시각이 포함되어야 합니다.
import json
from django.http import JsonResponse
from django.views import View
from user.models import User
from .models import Post
class PostView(View):
def post(self, request):
try:
data = json.loads(request.body)
email = data['email']
image_url = data['image_url']
content = data['content']
if not User.objects.filter(email=email).exists():
return JsonResponse({'message': 'INVALID_USER'}, status=401)
user = User.objects.get(email=email)
Post.objects.create(user=user, image_url=image_url, content=content)
return JsonResponse({'message': 'SUCCESS'}, status=200)
except KeyError:
return JsonResponse({'message': 'KEY_ERROR'}, status=400)
----------------------- 👇 여기부터 게시물 표출 -----------------------
def get(self, request):
posts = Post.objects.all()
post_list = []
for post in posts:
post_list.append(
{
'user_name' : post.user.name,
'image_url' : post.image_url,
'content' : post.content,
'created_at': post.created_at
}
)
return JsonResponse({'posts': post_list}, status=200)
from django.urls import path, include
urlpatterns = [
path('user', include('user.urls')),
path('posting', include('posting.urls'))
]
posting 앱에 urls.py 파일 생성하기
from django.urls import path
from posting.views import PostView
urlpatterns = [
path('', PostView.as_view()),
]