Django CRUD

Ryu Honggyu·2024년 8월 16일

Django

목록 보기
8/19
post-thumbnail

CRUD 란?

  • CRUD는 대부분의 컴퓨터 소프트웨어가 가지는 기본적인 데이터 처리 기능인 Create(생성), Read(읽기), Update(갱신), Delete(삭제)를 묶어서 일컫는 말.
  • CMS 등 정보를 관리하는 서비스라면 웬만해선 CRUD 를 모두 구현함.

CMS

  • Contents Management System. 웹사이트나 어플리케이션의 컨텐츠 등을 관리하는 시스템.
  • UI 를 통해 CRUD 작업을 쉽게 수행할 수 있도록 도와줌.
CRUD 기능CMS에서의 역할
Create새로운 컨텐츠를 생성.
Read기존의 컨텐츠를 조회하고 표시.
Update기존 컨텐츠를 수정.
Delete필요 없는 컨텐츠를 삭제.

Create 기능 구현

  • 새로운 Article 을 작성하는 단계다.

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. 템플릿 작성

  • 사용자로부터 제목과 내용을 입력받는 폼을 생성.
<!-- new.html -->
{% 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 를 표시.
<!-- 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. 템플릿에 표시

  • 전달된 데이터를 화면에 출력.
<!-- articles.html -->
{% 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 기능 구현

  • 작성했던 Article 을 수정하는 단계다.

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. 수정 폼 템플릿

  • 수정할 글의 제목과 내용을 입력받는 폼을 생성.
<!-- edit.html -->
{% 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 기능 구현

  • 특정 Article 을 삭제하는 단계다.

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. 삭제 버튼 생성

  • 상세 페이지에서 글을 삭제하는 버튼을 추가.
<!-- article_detail.html -->
{% 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 %}

참고자료

profile
알고리즘 & 웹 & CS & AI

0개의 댓글