
accountapp > views.py 에서 GET, POST 요청에 따라 각각 다른 문자열을 보여주도록 hello_world 함수를 변경
# accountapp > views.py
def hello_world(request):
text = "POST METHOD" if request.method == "POST" else "GET METHOD"
return render(request, 'accountapp/hello_world.html', context={'text': text})
아래 html 코드는 django 웹 프레임워크를 사용하여 작성된 간단한 폼이다. 사용자가 서버에 POST 방식으로 제출할 수 있도록 만든 간단한 예제이다.
<!-- accountapp > templates > accountapp > hello_world.html -->
{% extends "base.html" %}
{% block content %}
<div style="height: 20rem; background-color: #38df81; border-radius: 1rem; margin: 2rem;">
<h1>
TEST
</h1>
<form action="/account/hello_world/" method="post">
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="POST">
</form>
<h1>
{{ text }}
</h1>
</div>
{% endblock %}
<form> 태그:action="/account/hello_word/" : 폼 데이터가 제출될 서버의 URL 을 지정한다. 여기서는 /account/hello_world/경로로 POST 요청을 보낸다.method="post" : 폼 데이터를 서버로 보내는 방식을 POST로 설정한다.{% crsf_token %}:CSRF token missing 에러가 발생한다.Cross Site Request Forgery(CSRF)란 사용자가 자신의 의지와 무관하게 악의적인 요청을 보내도록 만드는 공격 방법 중 하나인데, 해당 태그는 CSRF 공격을 방지하는 데 중요한 역할을 한다.<input type="submit">class="btn btn-primary" : Bootstrap CSS 프레임워크의 클래스를 사용하여 버튼을 스타일링 한다. 클래스 btn, btn-primary를 사용한 것으로 btn은 기본 버튼 스타일을, btn-primary는 파란색 배경의 버튼 스타일을 적용한다. value="POST" : 버튼에 표시될 텍스트이다. 해당 버튼을 클릭하면 폼이 제출되고, 'action'에 지정된 URL로 데이터가 POST 방식으로 전달된다.{{ text }}