"장고 데이터 입력받기"의 두 판 사이의 차이

Pywiki
둘러보기로 가기 검색하러 가기
8번째 줄: 8번째 줄:
  
 
== GET으로 입력받기 ==
 
== GET으로 입력받기 ==
request.GET.get('name태그 이름') 형태로 GET으로 입력된 데이터를 받을 수 있다.
+
사전처럼 그 키로 값을 받아온다. request.GET 안에 데이터가 담긴다. 사전의 규약을 그대로 따라서 <code>request.GET['name속성']</code> 형태는 없으면 에러를 반환, <code>request.GET.get('name속성')</code> 형태는 None을 반환한다.(항상 문자열)'변수'가 없으면 KeyError를 발생시키고, 조건에 맞는 객체가 없으면 <code>객체.DoesNotExist</code> 에러가 발생한다.
  
  
 
HTML에서 form태그를 다음과 같이 작성한다.<syntaxhighlight lang="html+django">
 
HTML에서 form태그를 다음과 같이 작성한다.<syntaxhighlight lang="html+django">
 
     <form method="get" action="{% url 'utility:compound_interest' %}">
 
     <form method="get" action="{% url 'utility:compound_interest' %}">
         <p><label>얼마 넣을래? : <input type="text" value='{{principal}}' name="principal"></label></p>
+
         <p><label>얼마 넣을래? : <input type="text" value='{{ principal.value|default_if_none:"" }}' name="principal"></label></p>
         <p><label>이자율은? 단위는 % : <input type="text" value='{{interest_rate}}' name="interest_rate">%</label></p>
+
        <!-- .value가 없어도 된다. .value는 필요에 따라 붙이면 OK. -->
 +
         <p><label>이자율은? 단위는 % : <input type="text" value='{{ interest_rate|default_if_none:"" }}' name="interest_rate">%</label></p>
 
         <p><input type="submit" value="Submit"></p>
 
         <p><input type="submit" value="Submit"></p>
 
         <p>최종적으로 받는 금액은 {{result}}야.</p>
 
         <p>최종적으로 받는 금액은 {{result}}야.</p>
37번째 줄: 38번째 줄:
  
 
== POST로 입력받기 ==
 
== POST로 입력받기 ==
 +
GET과 동일하다. request.POST['name속성'] 혹은 request.POST.get('name속성') 형태로 전달받은 변수의 값들을 확인할 수 있다.(항상 문자열)
 +
 +
form에서 method를 post로 바꿔주고, view에서 GET 대신 POST를 넣어주면 된다.
  
 
= Form을 사용한 입력받기 =
 
= Form을 사용한 입력받기 =
 +
 +
=== forms.py 만들기 ===
 +
앱을 안에 forms.py를 만들어준다.<syntaxhighlight lang="python">
 +
from django import forms
 +
 +
class Compound_interest_form(forms.Form):
 +
    principal = forms.IntegerField()
 +
    interest_rate = forms.FloatField()
 +
    how_many = forms.IntegerField()
 +
    additional = forms.IntegerField(required=False)
 +
</syntaxhighlight>
 +
 +
=== 뷰 작성하기 ===
 +
<syntaxhighlight lang="python">
 +
def compound_interest(request):
 +
    #  폼을 통해 들어온 데이터를 받는다.
 +
    principal = request.GET.get('principal')
 +
    interest_rate = request.GET.get('interest_rate')
 +
    how_many = request.GET.get('how_many')
 +
    additional = request.GET.get('additional')
 +
    result = 0  # 아무 것도 넣지 않았을 때 반환.
 +
    form = Compound_interest_form(request.GET)  # 데이터를 폼에 대응.
 +
    if form.is_valid():  # 폼이 정상적일 때에만 진행.
 +
        # 연산은 생략.
 +
       
 +
    context = {'result':result,
 +
        form':form,
 +
              }
 +
    return render(request, 'utility/compound_interest.html', context)
 +
</syntaxhighlight>
 +
 +
=== 탬플릿 작성하기 ===
  
 
= 자료 검증 =
 
= 자료 검증 =
 
그냥 받기만 해선 해당 자료로 연산할 때 에러가 뜨기도 한다. 이를 위해선 form을 사용한 검증이 되면 편하다.
 
그냥 받기만 해선 해당 자료로 연산할 때 에러가 뜨기도 한다. 이를 위해선 form을 사용한 검증이 되면 편하다.
 
[[분류:7-0. 장고 중급 튜토리얼]]
 
[[분류:7-0. 장고 중급 튜토리얼]]

2021년 8월 20일 (금) 17:17 판

1 개요

장고에서 사용자로부터 데이터를 입력 받는 방법에 대해 살펴보자.

2 단순 입력받기

간단하지만 그닥 권하지 않는다. 간단한 기능이라도 form을 통해 오류검사를 받는 편이 정신건강에 더 좋다.

2.1 URL주소로 입력받기

2.2 GET으로 입력받기

사전처럼 그 키로 값을 받아온다. request.GET 안에 데이터가 담긴다. 사전의 규약을 그대로 따라서 request.GET['name속성'] 형태는 없으면 에러를 반환, request.GET.get('name속성') 형태는 None을 반환한다.(항상 문자열)'변수'가 없으면 KeyError를 발생시키고, 조건에 맞는 객체가 없으면 객체.DoesNotExist 에러가 발생한다.


HTML에서 form태그를 다음과 같이 작성한다.

    <form method="get" action="{% url 'utility:compound_interest' %}">
        <p><label>얼마 넣을래? : <input type="text" value='{{ principal.value|default_if_none:"" }}' name="principal"></label></p>
        <!-- .value가 없어도 된다. .value는 필요에 따라 붙이면 OK. -->
        <p><label>이자율은? 단위는 % : <input type="text" value='{{ interest_rate|default_if_none:"" }}' name="interest_rate">%</label></p>
        <p><input type="submit" value="Submit"></p>
        <p>최종적으로 받는 금액은 {{result}}야.</p>
    </form>

view를 다음과 같이 작성한다.

def compound_interest(request):
    #  GET으로 들어온 데이터를 받는다.
    principal = request.GET.get('principal')
    interest_rate = request.GET.get('interest_rate').
    # 연산을 하자.
    if interest_rate and principal and how_many:
        principal = float(principal)
        interest_rate = float(interest_rate)
        how_many = float(how_many)
    # 데이터를 담을 사전.
    context = {'principal': principal,
               'interest_rate': interest_rate,
               'result':result,
               }
    return render(request, 'utility/compound_interest.html', context)

2.3 POST로 입력받기

GET과 동일하다. request.POST['name속성'] 혹은 request.POST.get('name속성') 형태로 전달받은 변수의 값들을 확인할 수 있다.(항상 문자열)

form에서 method를 post로 바꿔주고, view에서 GET 대신 POST를 넣어주면 된다.

3 Form을 사용한 입력받기

3.1 forms.py 만들기

앱을 안에 forms.py를 만들어준다.

from django import forms

class Compound_interest_form(forms.Form):
    principal = forms.IntegerField()
    interest_rate = forms.FloatField()
    how_many = forms.IntegerField()
    additional = forms.IntegerField(required=False)

3.2 뷰 작성하기

def compound_interest(request):
    #  폼을 통해 들어온 데이터를 받는다.
    principal = request.GET.get('principal')
    interest_rate = request.GET.get('interest_rate')
    how_many = request.GET.get('how_many')
    additional = request.GET.get('additional')
    result = 0  # 아무 것도 넣지 않았을 때 반환.
    form = Compound_interest_form(request.GET)  # 데이터를 폼에 대응.
    if form.is_valid():  # 폼이 정상적일 때에만 진행.
        # 연산은 생략.
        
    context = {'result':result,
        form':form,
               }
    return render(request, 'utility/compound_interest.html', context)

3.3 탬플릿 작성하기

4 자료 검증

그냥 받기만 해선 해당 자료로 연산할 때 에러가 뜨기도 한다. 이를 위해선 form을 사용한 검증이 되면 편하다.