Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from django.urls import path
from . import views


urlpatterns = [
path("posts/", views.retrieve_post_list, name="retrieve_post_list"),
path("posts/<int:id>", views.retrieve_post_detail, name="retrieve_post_detail"),
path("posts/create", views.create_post, name="create_post"),
path("posts/<int:id>/put/update", views.update_post_with_put, name="update_post_with_put"),
path("comments/create", views.create_comment_to_post, name="create_comment_to_post"),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기선 표현의 한계가 있긴 한데, 나중에는 REST 하게 작성하는 방법도 익혀두면 좋을 것 같음

ex) POST /api/comments/ , POST /api/comments/1

]
31 changes: 29 additions & 2 deletions django_girls_tutorial/step2/jinho/djangogirls/blog/api/views.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import json
from http.client import NOT_FOUND, OK
from http import HTTPStatus

from django.contrib.auth.models import User
from django.http import JsonResponse, QueryDict
from django.utils import timezone
from django.views.decorators.http import require_http_methods

from blog.models import Post
from blog.form import CommentForm
from blog.models import Post, Comment


def retrieve_post_list(request):
Expand Down Expand Up @@ -87,3 +88,29 @@ def update_post_with_put(request, id):

FYI, request.body 활용
"""


@require_http_methods(["POST"])
def create_comment_to_post(request):
body = request.POST
try:
post_of_comment = Post.objects.get(id=body["post_id"])
Comment on lines +94 to +97
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

post_id를 request_body로 넘겨줘도 되는데, path param으로 넘겨줘도 될 것 같음

POST" /api/comments/1" 요런 식으로

except Post.DoesNotExist:
return JsonResponse({"message": "Post를 찾을 수 없습니다."}, status=HTTPStatus.NOT_FOUND)
else:
comment_form = CommentForm(body)
if comment_form.is_valid():
comment = comment_form.save(commit=False)
comment.author = body["author"]
comment.post = post_of_comment
comment.text = body["text"]
comment.save()
return JsonResponse({
"comment": {
"id": comment.id,
"author": comment.author,
"post_id": comment.post.id,
"text": comment.text,
}
}, status=HTTPStatus.CREATED)
return JsonResponse({"message": "form is invalid"}, status=HTTPStatus.BAD_REQUEST)
44 changes: 42 additions & 2 deletions django_girls_tutorial/step2/jinho/djangogirls/blog/tests.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import json
from http.client import NOT_FOUND, OK
from http import HTTPStatus

from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse

from .models import Post
from .models import Post, Comment


class TestPostMixin:
Expand Down Expand Up @@ -172,4 +173,43 @@ def test_post_update_with_error_with_post_on_404(self):
self.assertEqual(post.text, "test text")
response = json.loads(response.content)
# And: 응답 메세지로 post를 찾을 수 없습니다. 를 리턴 해야 한다.
self.assertEqual(response["message"], "post를 찾을 수 없습니다.")
self.assertEqual(response["message"], "post를 찾을 수 없습니다.")


class TestCommentCreate(TestPostMixin, TestCase):
def setUp(self):
super().setUp()
self.post = Post.objects.create(author=self.author, title="test title", text="test text")

def test_create_comment_to_post(self):
# Given: request body가 주어지고
request_body = {"author": "test by jinho", "post_id": self.post.id, "text": "test comment"}

# When: create_comment_to_post api를 호출한다.
response = self.client.post(reverse("create_comment_to_post"), data=request_body)

# Then: 상태코드는 201이고
self.assertEqual(response.status_code, HTTPStatus.CREATED)
# And: 응답값에서 생성된 comment의 author, post_id, text를 리턴한다.
response = json.loads(response.content)["comment"]
self.assertEqual(response["author"], "test by jinho")
self.assertEqual(response["post_id"], self.post.id)
self.assertEqual(response["text"], "test comment")
# And: post의 comment는 1개이다.
self.assertEqual(Comment.objects.filter(post_id=self.post.id).count(), 1)

def test_create_comment_to_post_with_invalid_post(self):
# Given: request body에 유효하지 않은 post_id가 주어진다.
invalid_post_id = 369
request_body = {"author": "test by jinho", "post_id": invalid_post_id, "text": "test comment"}

# When: create_comment_to_post api를 호출
response = self.client.post(reverse("create_comment_to_post"), data=request_body)

# Then: 상태코드는 404이고
self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
# And: 응답메세지로 "Post를 찾을 수 없습니다."를 리턴한다.
message = json.loads(response.content)["message"]
self.assertEqual(message, "Post를 찾을 수 없습니다.")
# And: comment는 추가되지 않으므로 개수는 0개이다.
self.assertEqual(Comment.objects.all().count(), 0)