▶️ Django
[▶️Back-end] 메인 페이지에 좋아요, 싫어요 버튼 기능 구현 2차
로직이 잘 작동되는지 게시글 작성과 상세 내용을 보는 로직을 추가하는 글이에요.
큰 목차
글 작성 구현 시작
⚙️ core/settings.py
# Media files
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"
⚙️ articles/urls.py
더보기
더보기
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from .views import ArticleList, ArticleLike, ArticleCreate
app_name = "articles"
urlpatterns = [
...
path("create/", ArticleCreate.as_view(), name="articlecreate"), # 게시물 생성
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
⚙️ articles/forms.py
더보기
더보기
# forms.py
from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'model_prompt', 'texture_prompt', 'image', 'tags'] # 폼에서 수정할 필드를 지정
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'model_prompt': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
'texture_prompt': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
'tags': forms.TextInput(attrs={'class': 'form-control'}),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 선택 사항: 필드 속성 추가 (예: required 설정)
self.fields['title'].required = True # 제목 필드 필수 설정
self.fields['image'].required = True # 이미지 필드 필수 설정
⚙️ articles/views.py
더보기
더보기
# 게시물 작성하기
class ArticleCreate(LoginRequiredMixin, View): # 로그인된 사용자만 접근 가능
login_url = "/users/login/" # 로그인 안 돼 있으면 보내버림
def get(self, request):
form = ArticleForm()
content = {"form":form}
return render(request,"create.html", content)
def post(self, request):
form = ArticleForm(request.POST, request.FILES)
print("폼 데이터:", request.POST) # 디버깅을 위해 폼 데이터 출력
if form.is_valid():
print("폼이 유효합니다.")
article = form.save(commit=False) # 즉시 저장하지 않고 Article 객체 생성
article.user_id = request.user # 현재 로그인한 사용자 설정
article.save() # 변경 사항과 함께 저장
return redirect("articles:articledetail", article.pk)
else:
print("폼이 유효하지 않습니다. 오류:", form.errors) # 폼 오류 출력
context = {"form": form}
return render(request, "create.html", context)
🔝
상세 글 보기 구현 시작
⚙️ articles/urls.py
더보기
더보기
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from .views import ArticleList, ArticleLike, ArticleCreate, ArticleDetail
app_name = "articles"
urlpatterns = [
...
path("<int:id>/", ArticleDetail.as_view(), name="articledetail"), # 게시물 상세보기
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
⚙️ articles/views.py
더보기
더보기
# 게시물 상세보기
class ArticleDetail(LoginRequiredMixin, View):
login_url = "/users/login/"
def get(self, request, id):
article = get_object_or_404(Article, pk=id)
content = {
"article": article
}
return render(request, "detail.html", content)
🔝
'👥 최종 팀 프로젝트(250227~250331) > 구현 과정 ▶️' 카테고리의 다른 글
[▶️중간 점검] 2주 동안의 구현된 현황 (2) | 2025.03.17 |
---|---|
[▶️Front-end] 메인 페이지에 좋아요, 싫어요 버튼 기능 구현 (0) | 2025.03.06 |
[▶️Back-end] 메인 페이지에 좋아요, 싫어요 버튼 기능 구현 2차 (0) | 2025.03.06 |
[▶️Back-end] 메인 페이지에 좋아요, 싫어요 버튼 기능 구현 1차 (1) | 2025.03.04 |
[▶️Front-end] Bootstrap으로 화면 구성(회원 가입, 로그인, 로그아웃) (0) | 2025.03.03 |