Django request POST

HeeJune KIM·2023년 4월 6일
0

Django_Pinterest

목록 보기
8/13

html & .py 데이터 주고 받기

# views.py
from accountapp.models import HelloWorld

def hello_world(request):
   if request.method == "POST":
        tmp = request.POST.get('hello_world_input')
        world = HelloWorld()
        world.text = tmp
        world.save()
        return render(request, 'accountapp/hello_world.html', context={'hello_world_output': world})
    else:
        return render(request, 'accountapp/hello_world.html', context={'text': 'GET METHOD'})
<!-- hello_world.html -->
{%  extends 'base.html' %}

{%  block content %}

    <div style="border-radius: 1rem; margin: 2rem; text-align: center;">
        <h1 style="font-family: 'lobster', cursive;">
            Hellow world LIST
        </h1>

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

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

{% endblock %}

class="btn btn-primary"; -> bootstrap에서 제공하는 클래스

<input type="text" name="hello_world_input">
: hellow_world_input이라는 이름을 붙여서 데이터를 넘겨준다.

if request.method == "POST":
    tmp = request.POST.get('hello_world_input')
	world = HelloWorld()
    world.text = tmp
    world.save()
    return render(request, 'accountapp/hello_world.html', context={'hello_world_output': world})
: 넘겨받은 request중 POST 방식으로 받은 데이터에서 hello_world_input을 get한다. 
후에 db_sqllite3에 저장하고, .html로 객체를 넘겨준다. 
    

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

0개의 댓글

관련 채용 정보