파이썬/Django
Update
Mara7
2022. 9. 20. 00:13
LIST
- 페이지 상세보기일때, 업데이트 버튼이 나오도록 출력합니다.
- 라우팅 설정을 하기 위하여, myapp의 urls.py에 update의 path 값을 넣어줍니다.
@csrf_exempt
def update(request,id):
global topics
if request.method == 'GET':
# 사용자가 GET 으로 접속 : update라는 텍스트를 출력
for topic in topics:
if topic['id'] == int(id):
selectedTopic = {
"title":topic['title'],
"body":topic['body']
}
# update는 create와 다르게, 기존 데이터를 가져와야한다!
article = f'''
<form action="/update/{id}/" method="post">
<p><input type="text" name="title" placeholder="title" value={selectedTopic["title"]}></p>
<p><textarea name="body" placeholder="body">{selectedTopic['body']}</textarea></p>
<p><input type="submit"></p>
</form>
'''
return HttpResponse(HTMLTemplate(article, id))
elif request.method == 'POST':
#사용자가 POST 로 수정 -> 상세보기 페이지 이동 ->
title = request.POST['title']
body = request.POST['body']
# 값을 변경시켜준다.
for topic in topics:
if topic['id'] == int(id):
topic['title'] = title
topic['body'] = body
return redirect(f'/read/{id}')
반응형
LIST