[django] 댓글(comment) 앱(app) 생성하기

hyeyul·2020년 5월 7일
0

Django

목록 보기
5/8

comment 앱 생성

회원가입/로그인 앱을 생성했으니, 이제는 댓글 기능을 구현하는 앱을 생성해보려 한다.

django-admin startapp comment


├── __init__.py
├── admin.py
├── apps.py
├── migrations
│   └── __init__.py
├── models.py
├── tests.py
└── views.py

comment앱을 생성하고 tree로 보면 이렇게 파일들이 생성된 것을 볼 수 있다.

이제 insta_ex에서 settings.py에 들어가서 comment앱을 추가해준다.

INSTALLED_APPS = [
  # 'django.contrib.admin',
  #   'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'account',
      'comment',
  ]

이제 makemigrations와 migrate을 해주자.

  • makemigrations : models.py에서 적용한 변경사항이나 추가된 혹은 삭제된 사항들을 감지하여 파일로 생성
  • migrate : 적용되지 않은 migrations들을(설정값들을) 적용시키는 역할
python manage.py makemigrations

python manage.py migrate

모델 작성

from django.db import models
 
  class Comment(models.Model):
      name = models.CharField(max_length = 50)
      text = models.CharField(max_length = 500)
      created_at = models.DateTimeField(auto_now_add=True)
 

 class Meta:
     db_table = "comments"

Comment 클래스 만들어서 이름과 텍스트 필드를 만들어주었다.

CharField, DataTimeField Meta 클래스 등은 이전 블로그에서 설명했던 부분들이라서 생략한다.

뷰 작성

이제는 comment/views.py에 가서 다음 코드를 작성하였다.

1 import json
  2 from django.shortcuts import render
  3 from django.views import View
  4 from django.http import HttpResponse, JsonResponse
  5 from .models import Comment
  6
  7 # Create your views here.
  8
  9 class CommentView(View):
 10     def post(self,request):
 11         data = json.loads(request.body)
 12         try:
 13             Comment.objects.create(
 14                     name = data['name'],
 15                     text = data['text']
 16                     )
 17             return HttpResponse(status =200)
 18
 19         except KeyError:
 20             return JsonResponse({'message':'INVALID_KEYS'},status=400)
 21
 22
 23
 24     def get(self,request):
 25         comment_data = list(Comment.objects.values())
 26
 27         return JsonResponse({'data':comment_data},status =200)

CommentView라는 클래스를 만들고 그안에 GET,POST 함수를 만들어주었다.
댓글앱은 사용자로부터 데이터를 받아서 데이터를 생성하기도하고 그것을 사용자에게 보여주기도 하므로 GET,POST 두개 모두 적용하여야 한다.

경로 작성

이제 마지막으로, 최상위 urls.pycomment/urls.py에 가서 path를 작성해야한다.

@ insta_ex/urls.py
 
 16 from django.contrib import admin
 17 from django.urls import path,include
 18
 19 urlpatterns = [
 20
 21     path('account',include('account.urls')),
 22     path('comment',include('comment.urls')),
 23 ]
  @ comment/urls/py

  1 from django.urls import path
  2 from .views import CommentView
  3
  4 urlpatterns = [
  5     path('',CommentView.as_view()),
  6 ]

이제 잘 작동되는지 확인하면 된다.

http -v http://127.0.0.1:8000/comment name='misun' text='hello'
 
POST /comment HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 34
Content-Type: application/json
Host: 127.0.0.1:8000
User-Agent: HTTPie/2.1.0

{
    "name": "misun",
    "text": "hello"
}

HTTP/1.1 200 OK
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Thu, 07 May 2020 11:59:57 GMT
Server: WSGIServer/0.2 CPython/3.8.0
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

이렇게 나오면 성공이다..!

0개의 댓글