데이터 분석 기술 블로그

Django에 대하여(16)_ORM with view(Delete와 Update) 본문

백엔드

Django에 대하여(16)_ORM with view(Delete와 Update)

데이터분석가 이채은 2024. 4. 6. 09:00

1. Delete

1.1 Delete 기능 구현

# articles/urls.py

urlpatterns = [
    ...
    path('<int:pk>/delete/', views.delete, name='delete')
]
# articles/views.py

def delete(request, pk):
    article = Article.objects.get(pk=pk)
    article.delete()
    return redirect('articles:index')
<!-- articles/detail.html -->

<body>
  <h2>Detail</h2>
  ...
  <hr>
  <form action="{% url 'articles:delete' article.pk %}" method="POST">
    {% csrf_token %}
    <input type="submit" value="DELETE">
  </form>
  <a href="{% url 'articles:index' %}">[back]</a>
</body>

결과


2. Update

Update 로직을 구현하기 위해 필요한 view 함수의 개수는 몇 개일까요? 사용자 입력 데이터를 받을 페이지를 렌더링 하는 edit과 사용자가 입력한 데이터를 받아 DB에 저장하는 update, 이렇게 두 개가 있습니다.

 

2.1 edit 기능 구현

# articles/urls.py

urlpatterns = [
    ...
    path('<int:pk>/edit/', views.edit, name='edit')
]
# articles/views.py

def edit(request, pk):
    article = Article.objects.get(pk=pk)
    context = {
        'article': article,
    }
    return render(request, 'articles/edit.html', context)

 

수정 시 이전 데이터가 출력될 수 있도록 작성한다.

<!-- articles/edit.html -->

<h1>EDIT</h1>
<form action="#" method="POST">
  {% csrf_token %}
  <div>
    <label for="title">Title: </label>
    <input type="text" name="title" id="title value="{{ aritcle.title }}">
  </div>
  <div>
    <label for "content">Content: </label>
    <textarea name="content" id="content">{{ article.content }}</textarea>
  </div>
  <input type="submit">
</form>
<hr>
<a href="{% url 'articles:index' %}">[back]</a>

 

edit 페이지로 이동하기 위한 하이퍼링크 작성

<!-- articles/detail.html -->

<body>

  <a href="{% url 'articles:edit' article.pk %}">EDIT</a><br>
  <form action="{% url 'articles:delete' article.pk %}" method="POST">
    {% csrf_token %}
    <input type="submit" value="DELETE">
  </form>
  <a href="{% url 'articles:index' %}">[back]</a>
</body>

 

2.2 update 기능 구현

# articles/urls.py

urlpatterns = [
    ...
    path('<int:pk>/update/', views.update, name='update')
]
# articles/views.py

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('articles:detail', article.pk)

 

작성 후 게시글 수정 테스트

<!-- articles/edit.html -->

<h1>EDIT</h1>
<form action="{% url 'articles:update' article.pk %}" method="POST">
  {% csrf_token %}
  <div>
    <label for="title">Title: </label>
    <input type="text" name="title" id="title value="{{ aritcle.title }}">
  </div>
  <div>
    <label for "content">Content: </label>
    <textarea name="content" id="content">{{ article.content }}</textarea>
  </div>
  <input type="submit">
</form>
<hr>
<a href="{% url 'articles:index' %}">[back]</a>

 

결과