- Django
[게시글 기능 구현]
user가 1)모든 사용자들이 작성한 게시글을 볼 수 있는 페이지, 2)게시글을 작성할 수 있는 페이지, 3)유저가 작성한 게시글을 자세히 볼 수 있는 상세 페이지를 만들어 줘야한다.
urls.py(앱)작업 → views / templates 작업 + urls.py에서 변수 url 작업까지!
- 5-1) 먼저 새로만든 앱 settings.py, urls.py 작업 해주기 → 앞 TIL 확인
- 5-2) 새로운 앱 (community) models 작업 : 게시글 관련 앱이라 정의된 필드가 많음 + admin 파일까지 등록
- models.py
from django.db import models
from users.models import User
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add = True) # auto_now_add : 새로 만들어졌을때 자동생성
updated_at = models.DateTimeField(auto_now = True) # auto_now : 등록이 아닌 수정을 했을때
# one to many 일때 foreign key가 사용됨 (user와 게시글 관계)
# on_delete=models.CASCADE : user를 삭제 했을때 작성한 게시글 -> CASCADE 모두 없애겠다!
user = models.ForeignKey(User, on_delete=models.CASCADE)
# admin 페이지에서 게시글 작성 시 저장되는 게시글 제목 변경해주기
def __str__(self):
return str(self.title)
👉 makemigrations - migrate 해준뒤 admin 페이지에서 꼭 확인해주기!!!!
- admin.py
from django.contrib import admin
from community.models import Article
# Register your models here.
admin.site.register(Article)
- 5-3) 앱에 접근시 기본적으로 보여주는 index 페이지 만들기 | urls 작업
from django.shortcuts import redirect
from django.urls import path
from community import views
app_name = 'community'
# url 순서가 상관있을때가 있음..
urlpatterns = [
# 초기 페이지 설정 (/community/ 페이지 접속시 -> index.html 보여줌)
path('', views.index, name='index'),
path('<int:article_id>/', views.article_detail, name='article_detail'),
path('create_article/', views.create_article, name='create_article'),
]
- 5-4) Index : community에 접근시 기본적으로 보여주는 페이지 = db에 저장된 게시글 보여주는 페이지 templates / views 파일 작업
- 5-5) create_article : admin 페이지가 아닌 create_article페이지에서 게시글을 작성 할 수 있게 만들어 주는 templates / views 파일 작업
- 5-6) article_detail : index에서 article_id를 변수로 받는 url 설정 해주면 article_detail 페이지로 이동하는 templates / views 파일 작업
- views.py
from django.http import HttpResponse
from django.shortcuts import redirect, render
from community.models import Article
from django.shortcuts import get_object_or_404
# Create your views here.
def index(request):
# 여기서 모든 게시글을 보고 싶음 / ORM? python으로 db 조작 (객체와 디비 연결)
articles = Article.objects.all().order_by('-created_at') # db에 있는 Article 정보 다 가져와 + .order_by('-created_at') 생성된 역순!
context = {
'articles':articles
}
return render(request, 'index.html', context)
👉 작성된 게시글 다 불러오는 함수 : templates(index.html)에서 어떻게 보여줄지 정리
def create_article(request):
if request.method == 'GET': # 단순 주소창에 입력했을때
return render(request, 'create_article.html')
elif request.method == 'POST':
title = request.POST.get('title')
content = request.POST.get('content')
user = request.user
Article.objects.create(title=title, content=content, user=user) # 지금 사용자가 인증된 사용자?
return redirect('community:index')
👉 게시글 작성 요청이 들어오면 templates에서 정의된 title, content을 가져와 index.html 에서 보여준다 (index.html은 작성된 모든 게시글을 가져오는 페이지니까)
# url 안에 쓴 숫자와(article_id) db에 저장된 id(id) 와 같으면 render 해줘
def article_detail(request, article_id):
# article = Article.objects.get(id=article_id)
article = get_object_or_404(Article, id=article_id)
context = {
'article':article
}
return render(request, 'article_detail.html', context)
👉 변수 url에서 정의됐듯 '/community/article_id' 에 접속시 해당 id 번호를 가지고 있는 게시글을 templates(article_detail.html)에서 정의된 형태로 가져온다
- Index.html
<body>
<h1>게시글</h1>
{% for article in articles %}
<div>
<h3>{{ article.title }}</h3>
# '게시글 보러가기 click'에 하이퍼링크로 '/community/article.id/' 경로를 걸어둠
<a href="{% url 'community:article_detail' article.id %}"> 게시글 보러가기 click </a>
<hr />
</div>
{% endfor %}
</body>
</html>
- create_article.html
<body>
<h1> 게시글 작성 페이지 </h1>
<form action="{% url 'community:create_article' %}" method="POST">
{% csrf_token %}
<div>
<input type="text" name="title" id="title" placeholder="title" />
</div>
<hr />
<textarea name="content" id="content" cols="30" rows="15" placeholder="content"></textarea>
<input type="submit" />
</form>
</body>
- article_detail
</head>
# index.html 페이지에서 하이퍼링크를 타고 들어오면 보여주는 article_detail.html 페이지
<h2>제목 | {{ article.title }}</h2>
<h2>내용 | {{ article.content }}</h2>
<p>작성 일시 | {{ article.created_at }}</p>
<p>작성자 ID | {{ article.user }}</p>
<hr />
<body>
'woncoding > TIL' 카테고리의 다른 글
| TIL | 10.18.화 [Django] (0) | 2022.10.19 |
|---|---|
| TIL | 10.17.월 [머신러닝] (0) | 2022.10.17 |
| TIL | 10.13.목 [머신러닝 / Django🐢] (0) | 2022.10.14 |
| TIL | 10.12.수 [머신러닝 / Django🐢] (0) | 2022.10.12 |
| TIL | 10.11.화 [Django🐢] (0) | 2022.10.11 |