데이터 수정하기
📌 상세 페이지에 수정 버튼 생성
① detail.html에 버튼 생성.
(detail.html)
<h1>DETAIL PAGE</h1>
<h3>{{ b.name }}</h3>
<b>지은이</b><input type="text" value="{{ b.writer }}" disabled><br><br>
<b>조회수</b><input type="text" value="{{ b.hit }}" disabled><br><br>
<b>내용</b><br><textarea cols="80" rows="8" disabled>{{ b.content }}</textarea><br><br>
<a href="{% url 'index' %}"><button>HOME</button></a>
<a href="{% url 'update' b.id %}"><button>MOD</button></a>
<a href="{% url 'delete' b.id %}"><button>DEL</button></a>
② urls.py에 path 추가.
(books/urls.py)
from django.urls import path
from . import views
urlpatterns = [
path('index/', views.index, name="index"),
path('detail/<bpk>', views.detail, name="detail"),
path('delete/<bpk>', views.delete, name="delete"),
path('create/', views.create, name="create"),
path('update/<bpk>', views.update, name="update")
]
③ views.py에 함수 추가.
(books/views.py)
...
def update(request, bpk):
b = Books.objects.get(id=bpk)
context = {
"b" : b
}
return render(request, "books/update.html", context)
④ templates/books 폴더에 update.html 생성.
(update.html)
<h1>UPDATE PAGE</h1>
<b>제목</b><input type="text" value="{{ b.name }}"disabled><br><br>
<form method="post" name="updateForm">
{% csrf_token %}
<b>지은이</b><input name="bwriter" type="text" value="{{ b.writer }}"><br><br>
<b>조회수</b><input name="bhit" type="text" value="{{ b.hit }}"><br><br>
<b>내용</b><br><textarea name="bcontent" cols="80" rows="8">{{ b.content }}</textarea><br><br>
<button type="button" onclick="check()">DONE</button>
<a href="{% url 'index' %}"><button type="button">HOME</button></a>
</form>
<script>
function check() {
cf = document.updateForm;
if(!cf.bwriter.value) {
alert("지은이를 입력하세요!")
}
else if(!cf.bcontent.value) {
alert("내용을 입력하세요!")
}
else {
cf.submit()
}
}
</script>
⑤ views.py에서 update구현 추가.
(books/views.py)
...
def update(request, bpk):
b = Books.objects.get(id=bpk)
if request.method == "POST":
bw = request.POST.get("bwriter")
bh = request.POST.get("bhit")
bc = request.POST.get("bcontent")
b.writer, b.hit, b.content = bw, bh, bc
b.save()
return redirect("detail", bpk)
context = {
"b" : b
}
return render(request, "books/update.html", context)
데이터 수정하기 - 결과
📌 데이터 수정하기 - 결과
'Django' 카테고리의 다른 글
[Django] 사진 관련 설정 (0) | 2022.12.20 |
---|---|
[Django] 사진 CRUD(1) - 기본 세팅 (0) | 2022.12.20 |
[Django] DB 가져와서 CRUD(6) - 데이터 추가하기(C) (0) | 2022.12.19 |
[Django] 데이터 전송 방식과 Form 태그 (0) | 2022.12.19 |
[Django] DB 가져와서 CRUD(5) - 데이터 삭제하기(D) (0) | 2022.12.19 |
댓글