■ JITHub 개발일지 30일차
□ TIL(Today I Learned) ::
파이썬 Django 인스타그램 클론 코딩 기능 구현(POST, 댓글 기능)
1. Django 인스타그램 클론코딩
- 데코레이터 사용시 : @login_required(login_url ///)
login_url 뒷부분을 활용하여 로그인이 안되어있을 경우 특정 페이지로 이동할 수 있게 한다.
- 게시글에 이미지 업로드할 때 미리 세팅해야 하는 부분이 있다.
① settings.py
② import os
# media file 저장위치 지정 # ★
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/uploads/'
③ 프로젝트의 urls.py에서 urlpatterns += static(settings.MEDIA_URL, document_root=settings.MDEIA_ROOT)
④ models.py에서 업로드 경로 지정 ImageField(upload_to='post_pics')
⑤ form 태그에 enctype="multipart/form-data"속성을 추가
⑥ views.py에서 이미지 저장은 request.FILES['<image name>'] 와 같이 한다.
- URL은 기본적으로 트레일링 슬래시를 마지막 부분에 붙여야 한다.
- root(기본 경로)에는 트레일링 슬래시가 기본적으로 붙어있다고 생각할 수 있다.
- 게시글 관련 view 설정
def index(request):
if request.user.is_authenticated: # 사용자가 인증이 되었는지(로그인 되었는지)
all_post = PostModel.objects.all().order_by('-created_at')
return render(request, 'post/post/index.html', {'posts':all_post})
else:
return redirect('/sign-in')
def post_new(request):
if request.method == 'GET':
user = request.user.is_authenticated
if user:
return render(request, 'post/post/new_post.html')
return render(request, 'account/user/login.html')
elif request.method == 'POST':
user = request.user # 현재 로그인 한 사용자 불러오기
content = request.POST.get('my-content','')
image = request.FILES['image'] # 이미지 저장
if content == '':
return render(request, 'post/post/new_post.html', {'error':'글은 공백일 수 없습니다.'})
else:
my_post = PostModel.objects.create(author=user, image=image, content=content)
my_post.save()
return redirect('/')
@login_required
def post_delete(request, post_id):
my_post = PostModel.objects.get(id=post_id)
my_post.delete()
return redirect('/')
@login_required
def post_update(request, post_id):
my_post = PostModel.objects.get(id=post_id)
if request.method == 'GET':
post_form = PostForm(instance = my_post)
return render(request, 'post/post/update_post.html', {'post':my_post, 'form':post_form})
elif request.method == 'POST':
my_post.content = request.POST['my-content']
my_post.image = request.FILES['my-image']
my_post.save()
return redirect('/')
- 댓글 관련 view 설정
@login_required
def comment_detail(request, id):
my_post = PostModel.objects.get(id=id)
post_comment = CommentModel.objects.filter(post_id=id).order_by('created_at')
return render(request, 'post/post/comment_detail.html', {'post':my_post, 'comments':post_comment }) #'comment':post_comment
@login_required
def comment_write(request, id):
if request.method == "POST":
comment = request.POST.get('comment', '')
cur_post = PostModel.objects.get(id=id)
my_comment = CommentModel()
my_comment.comment = comment
my_comment.post = cur_post
my_comment.author = request.user
my_comment.save()
return redirect('/comment/detail/'+str(id))
@login_required
def comment_delete(request, id):
comment = CommentModel.objects.get(id=id)
current_post = comment.post_id
comment.delete()
return redirect('/comment/detail/'+str(current_post))
@login_required
def comment_update(request, id):
my_comment = CommentModel.objects.get(id=id)
if request.method == 'GET':
comment_form = PostForm(instance = my_comment)
return render(request, 'post/post/update_comment.html', {'comment':my_comment, 'form':comment_form})
elif request.method == 'POST':
my_comment.comment = request.POST['my-comment']
current_post = my_comment.post_id
my_comment.save()
return redirect('/comment/detail/'+str(current_post))
- 이미 작성되어있는 글을 업데이트할 때에는 아래와 같이 forms.py를 활용하여 인스턴스를 전달해주어야 한다.
위의 코드 중 업데이트뷰에 ~form = PostForm(instance = ...) 와 같이 전달하고 이 값을 return으로 렌더링한다.
from django import forms
from .models import PostModel, CommentModel
class PostForm(forms.ModelForm):
class Meta:
model = PostModel
fields = ['content','image']
class CommentForm(forms.ModelForm):
class Meta:
model = CommentModel
fields = ['comment']
- Post부분 urls.py
from django.urls import path
from . import views
app_name = 'post'
urlpatterns = [
path('', views.index, name = 'index'),
path('post-new/', views.post_new, name = 'post-new'),
path('post-delete/<int:post_id>/', views.post_delete, name = 'post-delete'),
path('post-update/<int:post_id>/', views.post_update, name = 'post-update'),
path('comment/detail/<int:id>/', views.comment_detail, name = 'comment-detail'),
path('comment/write/<int:id>', views.comment_write, name="comment-write"),
path('comment/delete/<int:id>', views.comment_delete, name="comment-delete"),
path('comment/update/<int:id>', views.comment_update, name="comment-update"),
]
2. 깃 커밋 메시지 설정하기
② vim .gitmessage.txt ③ 아래 내용 작성해넣기
################
# <타입> : <제목> 의 형식으로 제목을 아래 공백줄에 작성
# 제목은 50자 이내 / 변경사항이 "무엇"인지 명확히 작성 / 끝에 마침표 금지
# 예) Feat : 로그인 기능 추가/ 맨 앞글자는 대문자로
# 바로 아래 공백은 지우지 마세요 (제목과 본문의 분리를 위함)
################
# 본문(구체적인 내용)을 아랫줄에 작성
# 여러 줄의 메시지를 작성할 땐 "-"로 구분 (한 줄은 72자 이내)
- 1. 무엇을?
- 2. 왜?
################
# 꼬릿말(footer)을 아랫줄에 작성 (현재 커밋과 관련된 이슈 번호 추가 등)
# 예) Close #7
################
# feat : 새로운 기능 추가
# fix : 버그 수정
# docs : 문서 수정
# test : 테스트 코드 추가
# refact : 코드 리팩토링
# style : 코드 의미에 영향을 주지 않는 변경사항
# chore : 빌드 부분 혹은 패키지 매니저 수정사항
################
□ TIF(Today I Felt) ::
- 인스타그램 클론코딩의 게시글, 댓글 CRUD 기능들을 직접 완성해보았다. 아직 전체 코딩을 직접 빠른시간안에는 해내기 어렵지만, 당분간 계속 다시보면서 익혀나갈 필요가 있을 것 같다.
- 머신러닝 프로젝트 주제가 정해졌다. 아직 구체화는 되지 않았지만, 팀장으로써 순조롭게 진행될 수 있도록 계속 고민하게 된다. 팀원들이 마지막까지 만족할 수 있는 프로젝트가 되었으면 한다.
'DEV > Web 개발' 카테고리의 다른 글
Web 개발 :: 머신러닝 프로젝트 SA_TIL#33 (0) | 2022.10.20 |
---|---|
Web 개발 :: 파이썬 Django 인스타그램 코드 리뷰, 머신러닝_TIL#31 (0) | 2022.10.18 |
Web 개발 :: 파이썬 django 인스타그램 코드 리뷰, 머신러닝_TIL#29 (0) | 2022.10.13 |
Web 개발 :: 파이썬 django 인스타그램 코드 리뷰_TIL#28 (0) | 2022.10.12 |
파이썬 웹 프로그래밍 :: 10월 둘째주 WIL #06 (0) | 2022.10.11 |
댓글