작정하고 장고 _ 4/10

seoyeon·2023년 4월 11일
0

UDR

목록 보기
26/42

16강_GET, POST 프로토콜 실습

  • get : 주소창에 넣으면 자동으로 전송
  • post : 따로 설정, 사용하기 위해 html안에 form을 만들어줘야 함
    • form : 서버한테 보내는 요청 명세서
    • 글, 파일 첨부 시 form 안에 저장 (= 데이터 꾸러미, 서버로 보낼 내용)
<form action="/account/hello_world/" method="post">
      <input type="submit" class="btn btn-primary" value="POST">
      
</form>

→ 오류 발생

→ 장고, post 메소드 사용해서 서버에 요청을 보낼때는 csrf 토큰 생성해야함

{% csrf_token %}
  • accountapp - view.py : get과 post 나누는 코드 작성

17강_POST 통신을 이용한 DB 데이터 저장 실습

  • main html 파일에서 진행 (hello_world.html)

  • form에 내용 추가

<div>
	<input type="text" name="hello_world-input">
</div>
  • views.py의 POST에서 데이터 확인하는 작업 추가
if request.method == "POST":

	temp = request.POST.get('hello_world_input')
    
return render(request, 'accountapp/hello_world.html', context={'text': temp})
  • model.py의 HelloWorld 가져오기 (Alt + Enter)
new_hello_world = HelloWorld() # HelloWorld의 새로운 객체 생성
new_hello_world.text = temp # HelloWorld의 캐릭터필드(속성값) 지정
new_hello_world.save() #DB에 객체 저장

return render(request, 'accountapp/hello_world.html', context={'hello_world_output': new_hello_world})
# 문장이 아닌 객체 내보내기
  • hello_world.html 에 출력문 추가
{% if hello_world_output %}
<h1>
	{{ hello_world_output.text }}
</h1>
{% endif %}

→ 결과물(출력물)은 똑같지만 DB에 저장되고 있다는 차이 !!

profile
안녕하세용

0개의 댓글

관련 채용 정보