meong_j
기록하는 습관.
meong_j
전체 방문자
오늘
어제
  • 분류 전체보기 (176)
    • 개인 공부 정리 (0)
    • 서버 운영 (37)
      • Linux (36)
    • Frontend (11)
      • Vue.js (10)
    • Backend (70)
      • Java (4)
      • Python (22)
      • Django (38)
      • Spring (6)
    • Database (5)
      • Oracle (4)
      • MySQL (1)
      • MariaDB (0)
    • Android (14)
      • Kotlin (6)
    • 배포 (9)
      • Docker (8)
      • AWS (1)
    • IT_study (29)
      • Coding test (17)
      • 알고리즘 (5)
      • 스터디 (6)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • github

인기 글

반응형

태그

  • 이차원배열정렬
  • SASS Variables
  • DHCP
  • 테크커리어
  • dp #알고리즘
  • router-link
  • 개발자도서
  • 중첩라우트
  • django
  • 배포인프라
  • cpu사용률
  • 코틀린자료형
  • 리눅스방화벽
  • Proxy
  • dockersecret
  • Kotlin
  • 리눅스인증
  • 안드로이드adaptor
  • docker
  • gabagecollecter

최근 댓글

최근 글

250x250
hELLO · Designed By 정상우.
meong_j

기록하는 습관.

django 08.  POST 통신을 이용한 DB 데이터 저장 실습
Backend/Django

django 08. POST 통신을 이용한 DB 데이터 저장 실습

2021. 10. 5. 19:08
728x90
반응형

hello_world.html

{% extends 'base.html' %}
<!-- base.html 템플릿를 기반으로 안에 내용만 바꿔줌-->
{% block content %}

    <div style="border-radius: 1rem; margin: 2rem; text-align: center">
        <h1 style="font-family: 'Lobster', cursive;">
            Hello world List!
        </h1>

        <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>

<!--    서버 return    text 값 가져옴-->
        {% if hello_world_list %}
            {% for hello_world in hello_world_list %}
        <h1>
            {{ hello_world.text }}
        </h1>
            {% endfor %}
        {% endif %}
    </div>

{% endblock %}
  • input태그에 입력한 값 post버튼 누룰시 post방식으로 request
  • 서버 request받아 html로 다시 response
  • 저장한 데이터 불러와서 for구문으로 출력

 

views.py

def hello_world(request):

    if request.method == "POST":
        # hello_world_input이름의 input태그 값 가져오기
        temp = request.POST.get('hello_world_input')
        # HelloWorld 모델 가져오기
        new_hello_world = HelloWorld()
        new_hello_world.text = temp
        # db에 저장
        new_hello_world.save()

        # db에 저장한 데이터 불러오기
        # hello_world_list = HelloWorld.objects.all()
        # HttpResponseRedirect는 새로고침해도 기존정보 불러오지 않게 방지
        return HttpResponseRedirect(reverse('accountapp:hello_world'))
        # return render(request, 'accountapp/hello_world.html', context={'hello_world_list': hello_world_list})
    else:
        hello_world_list = HelloWorld.objects.all()
        return render(request, 'accountapp/hello_world.html', context={'hello_world_list': hello_world_list})
  • 입력값 request 받아 HelloWorld 테이블에 insert
  • 저장한 db값 불러오기
  • HttpResponseRedirect 로 기존 정보 새로고침되도 불러오지 않게 대비함
  • urls.py에 있는 app_name(accountapp)으로 주소 불러와서 쓰기

 

 

결과 화면

 

반응형

'Backend > Django' 카테고리의 다른 글

django 10. CreateView 를 통한 회원가입 구현  (0) 2021.10.05
django 09. 장고의 CRUD, class Based View  (0) 2021.10.05
django 07. model, DB 연동하기  (0) 2021.10.05
django 06. static 설정 및 css 파일 분리  (0) 2021.10.05
django 05. style, 구글 폰트, 네이버 글꼴을 통해 Header, Footer 꾸미기  (0) 2021.10.05
    'Backend/Django' 카테고리의 다른 글
    • django 10. CreateView 를 통한 회원가입 구현
    • django 09. 장고의 CRUD, class Based View
    • django 07. model, DB 연동하기
    • django 06. static 설정 및 css 파일 분리
    meong_j
    meong_j
    #it #개발일기 #개발공부 #개발자 #백앤드 #생각정리 #시간은 실력에 비례한다 #뭐든지 꾸준히 열심히 #오늘의 내가 내일의 나를 만든다

    티스토리툴바