from django.db import models
class User(models.Model):
email = models.EmailField(max_length=50, unique=True)
from django.urls import path
from .views import SignupView, LoginView
# *을 남발하지 않기.
(urls.W002) Your URL pattern '/user' has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'.
해결 : 장고의 권장사항이다. 그러므로 원래 알던데로 진행하면 된다.(수정 완료)
(프로젝트의 urls.py)
urlpatterns = [
path('account', include('account.urls')),
]
(앱의 urls.py)
from django.urls import path
from .views import SignupView, LoginView
urlpatterns = [
path('/user', SignupView.as_view()),
path('/login', LoginView.as_view()),
]
data = json~
예외처리아직 쿼리를 날린다는 말이 뭔 말인지 잘 이해가 안 되어서 한 불필요한 작업이었음.
-이유 : 이미 User.~를 통해 쿼리를 날려 데이터에서 필요한 자료를 가져올 수 있다. 불필요한 변수였다.
comment :
-client에서 들어온 값 중 이메일 필터 쿼리를 날려 존재하는 이메일일 경우인지 확인.
-(마찬가지로) 비밀번호 필터 쿼리를 날려 존재하는 비밀번호인지 확인.
-이메일과 비밀번호가 유효한 포맷인지 검사하여 유효하면 값 만들기 진행.
예시로 만일 데이터가 email=~~ password=~~ 로 오는 것이 아니라 emailadkfj=~~ apsdkfjsa=~~~처럼 키 내용이 잘못 와버리는 경우 예외 처리로 키 에러 냄
app 설치 후 기본 세팅 : 다루는 데이터가 달라지면 앱을 분리한다.
models.py 완성하기
from django.db import models
from account.models import User
# 외부 폴더에서 가져온 클래스. 이거 때문에 한참 헤맴.
class Posting(models.Model):
upload_time = models.DateTimeField(auto_now_add=True)
# 실시간을 가져오는 방법, 초까지 기록된다.
img_url = models.CharField(max_length=1000)
user = models.ForeignKey(User, on_delete=models.CASCADE)
# 외부 폴더에서 받아온 클래스는 ''를 붙이지 않는다
class Meta:
db_table = "postings"
3-1. 등록 클래스
(코드)
import json
from django.views import View
from django.http import JsonResponse
from .models import Posting
from account.models import User
class PostingView(View):
def post(self, request):
#딕셔너리 모양으로 받아들여진 정보(httpie에 입력한 정보)
data = json.loads(request.body)
user = User.objects.get(email=data['email'])
posting = Posting.objects.create(
img_url = data["img_url"],
user = user
#Time은 알아서 import, 입력 필요 없음.
)
return JsonResponse({"message" : "SUCCESS"}, status=200)
3-2. 표출
class ShowView(View):
def get(self, request):
shows = Posting.objects.all()
result = []
for show in shows:
my_dict = {
'update_time' : show.upload_time,
'img_url' : show.img_url,
'user' : show.user.email,
}
result.append(my_dict)
return JsonResponse({"result" : result}, status=200)
from django.urls import path
from .views import PostingView, ShowView
urlpatterns = [
path('/posting', PostingView.as_view()),
path('/show', ShowView.as_view()),
]
프로젝트 urls.py
from django.urls import path, include
urlpatterns = [
path('account', include('account.urls')),
path('posting', include('posting.urls')),
]
특별한 것은 없다.
posting app 구현 : 기능이 바뀌면 앱이 바뀌어야 함. 이미 만든 미션4를 응용(게시글과 댓글은 같은 위치에 같은 기능이니까!)
models.py
class Comment(models.Model):
update_time = models.DateTimeField(auto_now_add=True)
comment = models.CharField(max_length=2000)
img_url = models.ForeignKey(Posting, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
db_table = "comments"
이 코드에서는 이미지와 유저가 포린키를 하고 있다. 왜냐면 코멘트가 두 가지를 모두 참조하고 있기 때문.(one to many)
class CommentView(View):
def post(self, request):
data = json.loads(request.body)
img_url = Posting.objects.get(img_url=data['img_url'])
user = User.objects.get(email=data['email'])
comment = Comment.objects.create(
comment = data["comment"],
img_url = img_url,
user = user
)
return JsonResponse({"message":"SUCCESS"}, status=200)
댓글을 등록해야 하는 것이니 POST이용. 그리고 이미지와 유저가 각각 포린키이니 데이터를 가져오고 코멘트로 크리에이트 함.(포린키만 두 개지 여태 했던 것과 매우 유사)
그리고 코멘트를 보여주는 GET
(코드)
class CommentShowView(View):
def get(self, request):
commentshows = Comment.objects.filter(img_url=1)
# id 값이 1번인 게시글의 등록된 댓글들만(그래서 filter, get아님) 출력
result = []
for commentshow in commentshows:
my_dict = {
'user' : commentshow.user.email,
'comment' : commentshow.comment,
}
result.append(my_dict)
return JsonResponse({"result" : result}, status=200)
그 외 url 추가하는 법은 앞서 한 내용과 유사하여 코드 생략.
크게 에러가 나지 않고 실습을 진행했다. 코드에 점점 익숙해지고 있으니 다음 과제도 잘 실행해보자.