CRUD 란?
- CRUD는 대부분의 컴퓨터 소프트웨어가 가지는 기본적인 데이터 처리 기능인 Create(생성), Read(읽기), Update(갱신), Delete(삭제)를 묶어서 일컫는 말.
- CMS 등 정보를 관리하는 서비스라면 웬만해선 CRUD 를 모두 구현함.
CMS
- Contents Management System. 웹사이트나 어플리케이션의 컨텐츠 등을 관리하는 시스템.
- UI 를 통해 CRUD 작업을 쉽게 수행할 수 있도록 도와줌.
| CRUD 기능 | CMS에서의 역할 |
|---|
| Create | 새로운 컨텐츠를 생성. |
| Read | 기존의 컨텐츠를 조회하고 표시. |
| Update | 기존 컨텐츠를 수정. |
| Delete | 필요 없는 컨텐츠를 삭제. |
Create 기능 구현
1. URL 설정
- /articles/new/` URL로 접속 시 새로운 글 작성 페이지를 보여줌.
# articles/urls.py
urlpatterns = [
path("new/", views.new, name="new"),
path("create/", views.create, name="create"),
]
2. 뷰 함수 추가
# articles/views.py
def new(request):
return render(request, "new.html")
3. 템플릿 작성
- 사용자로부터 제목과 내용을 입력받는 폼을 생성.
{% extends "base.html" %}
{% block content %}
<h1>New Article</h1>
<form action="{% url 'create' %}" method="POST">
{% csrf_token %}
<label for="title">제목</label>
<input type="text" name="title" id="title"><br><br>
<label for="content">내용</label>
<textarea name="content" id="content" cols="30" rows="10"></textarea><br><br>
<button type="submit">저장</button>
</form>
{% endblock content %}
4. 데이터 처리
- 작성된 데이터를 받아서 DB에 저장하는 뷰를 구현함.
# articles/views.py
def create(request):
title = request.POST.get("title")
content = request.POST.get("content")
article = Article(title=title, content=content)
article.save()
context = {
"article": article,
}
return render(request, "create.html", context)
5. 생성 완료 템플릿
- 글이 성공적으로 작성되었다는 메시지
create.html 를 표시.
{% extends "base.html" %}
{% block content %}
<h1>'{{article.title}}' 작성 완료</h1>
<a href="{% url 'articles' %}">목록으로</a>
{% endblock content %}
Read 기능 구현
1. 모델에서 데이터 가져오기
# articles/views.py
from .models import Article
def articles(request):
articles = Article.objects.all()
context = {
"articles": articles,
}
return render(request, "articles.html", context)
2. 템플릿에 표시
{% extends "base.html" %}
{% block content %}
<h1>Articles</h1>
<ul>
{% for article in articles %}
<li>
<div>글 번호 : {{ article.id }}</div>
<div>글 제목 : {{ article.title }}</div>
<div>글 내용 : {{ article.content }}</div>
<br>
</li>
{% endfor %}
</ul>
{% endblock content %}
Update 기능 구현
1. URL 설정
/articles/<pk>/edit/ URL로 접속 시 수정 폼 페이지를 보여줌.
# articles/urls.py
urlpatterns = [
path("<int:pk>/edit/", views.edit, name="edit"),
path("<int:pk>/update/", views.update, name="update"),
]
2. 뷰 함수 추가
- 수정할 글을 보여주는 뷰와 수정 사항을 처리하는 뷰를 구현함.
# articles/views.py
def edit(request, pk):
article = Article.objects.get(pk=pk)
context = {
"article": article,
}
return render(request, "edit.html", context)
def update(request, pk):
article = Article.objects.get(pk=pk)
article.title = request.POST.get("title")
article.content = request.POST.get("content")
article.save()
return redirect("article_detail", article.pk)
3. 수정 폼 템플릿
- 수정할 글의 제목과 내용을 입력받는 폼을 생성.
{% extends "base.html" %}
{% block content %}
<h1>Update Article</h1>
<form action="{% url 'update' article.pk %}" method="POST">
{% csrf_token %}
<label for="title">제목</label>
<input type="text" name="title" id="title" value="{{ article.title }}"><br><br>
<label for="content">내용</label>
<textarea name="content" id="content" cols="30" rows="10">{{ article.content }}</textarea><br><br>
<button type="submit">저장</button>
</form>
{% endblock content %}
Delete 기능 구현
1. URL 설정
/articles/<pk>/delete/ URL로 접속 시 삭제 처리.
# articles/urls.py
urlpatterns = [
path("<int:pk>/delete/", views.delete, name="delete"),
]
2. 뷰 함수 추가
# articles/views.py
def delete(request, pk):
article = Article.objects.get(pk=pk)
if request.method == "POST":
article.delete()
return redirect("articles")
return redirect("article_detail", article.pk)
3. 삭제 버튼 생성
{% extends "base.html" %}
{% block content %}
<h2>글 상세 페이지</h2>
<p>제목: {{ article.title }}</p>
<p>내용: {{ article.content }}</p>
<p>작성일시: {{ article.created_at }}</p>
<p>수정일시: {{ article.updated_at }}</p>
<a href="{% url 'articles' %}"><button>목록 보기</button></a>
<hr>
<form action="{% url 'delete' article.pk %}" method="POST">
{% csrf_token %}
<input type="submit" value="글삭제">
</form>
{% endblock content %}
참고자료