어느 정도 backend part가 만들어져서 이제는 frontend 쪽을 손 보았다.
login이 된 user가 게시글(post)를 작성하고, '게시글 저장' 버튼을 누르면 database로 입력 내용이 저장되는 것을 구현해 보려 한다.
url 주소
http://127.0.0.1:5500/frontend/postdetail.html
Frontend 화면
로그인이 된 사용자가 게시글을 작성하고 '게시글 저장' 버튼을 클릭하면, 입력한 세 가지 정보(이미지(image), 제목(title), 내용(content))가 DB에 저장된다.
코드를 보면 다음과 같다.
frontend/postdetail.html
<h1 style="text-align: center; margin: 100px;">게시글 작성</h1>
<form style=" margin: 100px; padding: 50px; border: solid 1px black;">
<div class="row mb-3">
<label class="col-sm-2 col-form-label">이미지 업로드</label>
<div class="col-sm-10">
<input type="file" class="form-control" name="image" id="image" style="margin-bottom: 20px;">
</div>
</div>
<div class="row mb-3">
<label class="col-sm-2 col-form-label">제목</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="제목을 입력하세요">
</div>
</div>
<div class="row mb-3">
<label class="col-sm-2 col-form-label">내용</label>
<div class="col-sm-10">
<textarea style="height: 100px;" class="form-control" placeholder="내용을 입력하세요" rows="10" cols="30" id="content" name="content"></textarea>
</div>
</div>
<a href="index.html">
<button type="button" class="btn btn-dark" style="float: right;" onclick="handlePostSubmit()">게시글 저장</button>
</a>
</form>
button의 onclick='handlePostSubmit()'이 클릭되면 아래의 코드가 실행된다.
api.js
async function handlePostSubmit(){
const formData = new FormData();
const image = document.getElementById("image").files[0]
const title = document.getElementById("title").value
const content = document.getElementById("content").value
const token = localStorage.getItem("access")
formData.append("image", image)
formData.append("title", title)
formData.append("content", content)
const response = await fetch('http://127.0.0.1:8000/posts/', {
headers:{
'Authorization': `Bearer ${token}`
},
method:'POST',
body:formData
})
console.log(response)
}
frontend로부터 받아온 정보를 formData에 넣고, image, title, content 값들을 각각 가져와서 적당한 이름의 vriable에 넣는다. token 값은 localStorage에서 가져온다. 이렇게 가져온 값들을 'formData.append()' method를 통해 key와 value 값으로 정리하여 formData에 넣고 이 값을 body에 실어서 fetch로 적힌 url 주소로 보내진다. 여기서 method는 POST.
urls.py
from django.urls import path
from posts import views
urlpatterns = [
path('posts/', views.PostView.as_view(), name='post_view'),
]
urls.py에서 PostView로 넘어간다.
views.py
from rest_framework.views import APIView
from rest_framework import status, permissions
from rest_framework.response import Response
from posts.serializers import PostCreateSerializer
class PostView(APIView):
permission_classes = [permissions.IsAuthenticated]
def post(self, request):
serializer = PostCreateSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=request.user)
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
PostView에서 인증을 확인하고 받아온 data 값을 PostCreateSerializer을 통해 직렬화(JSON)를 거치고, 이 검증 과정을 통과한 값을 DB에 저장한다.
serializers.py
from rest_framework import serializers
from posts.models import Post
class PostCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ("title", "content", "image")
이제 DB에 Post 값들이 잘 저장된 것을 확인할 수 있다.
'Computer Programming > AI' 카테고리의 다른 글
TIL_Machine Learning(2) (0) | 2023.10.17 |
---|---|
TIL_Machine Learning (0) | 2023.10.16 |
WIL_아홉 번째 주 (0) | 2023.10.08 |
TIL_Django REST Framework(DRF)의 serializers 사용 방법 (0) | 2023.10.07 |
TIL_Cookie/Session 방식과 Token 방식의 차이점 (0) | 2023.10.05 |