본문 바로가기
기타/django

작정하고 장고 - GET, POST

by 방배킹 2023. 4. 10.

16강 : GET, POST 프로토콜 실습

form 태그

hello_world.html에 form 태그를 추가해준다.

{% extends 'base.html' %}

{% block content %}
    <div style="height: 20rem; background-color: #38df81; border-radius: 1rem; margin: 2rem;">
      <h1>
          Testing
      </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 태그 내부에 POST 타입의 input 태그를 만들어준다.
이때 {% csrf_token %} 를 추가해줘야 하는데

해당 구문은 장고를 이용해서 POST method를 사용해서 서버에 요청을 보낼때 항상 form 안에 명시해줘야한다.
(보안기능중 하나이다.)


해당 구문을 추가하지 않으면 다음과 같이 오류가 발생한다.

veiws.py

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.

def hello_world(request):

    if request.method == "POST":
        return render(request, 'accountapp/hello_world.html', context={'text': 'POST METHOD!!!'})
    else:
        return render(request, 'accountapp/hello_world.html', context={'text': 'GET METHOD!!!'})

만약 request method가 POST 형식일 경우 context라는 꾸러미안에 text라는 이름가진 데이터에 POST METHOD!!!를 아닐 경우 GET METHOD!!!를 넣어준다.

즉, 이름이 text, 값은 각각 POST METHOD!!!, GET METHOD!!! 이다.

그러면 hello_world.html에 {{ text }} 를 작성하면 text위치에 해당하는 값이 출력된다.


버튼을 누르면 다음과 같이 변경된다.

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

<form action="/account/hello_world/" method="post">
            {% csrf_token %}
            <div>
                <input type="text" name="hello_world_input">
            </div>
            <div>
                <input type="submit" class="btn btn-primary" value="POST">
            </div>

        </form>
        
        {% if hello_world_output %}
        <h1>
            {{ hello_world_output.text }}
        </h1>
        {% endif %}

name 이 hello_world_input인 text type의 input 태그를 만든다.

def hello_world(request):

    if request.method == "POST":
        temp = request.POST.get('hello_world_input')
        new_hello_world = helloWorld()
        new_hello_world.text = temp
        new_hello_world.save()
        return render(request, 'accountapp/hello_world.html', context={'hello_world_output': new_hello_world})

    else:
        return render(request, 'accountapp/hello_world.html', context={'text': 'GET METHOD!!!'})

temp라는 변수에 hello_world_input에서 들어온 정보를 저장하고
해당 정보를 helloWorld 객체를 새로 만들어 해당 객체의 text에 저장을 한뒤
데이터베이스에 저장을 한다.

댓글