"장고 데이터 입력받기"의 두 판 사이의 차이
둘러보기로 가기
검색하러 가기
2번째 줄: | 2번째 줄: | ||
장고에서 사용자로부터 데이터를 입력 받는 방법에 대해 살펴보자. | 장고에서 사용자로부터 데이터를 입력 받는 방법에 대해 살펴보자. | ||
− | = URL주소로 입력받기 = | + | = 단순 입력받기 = |
+ | |||
+ | == URL주소로 입력받기 == | ||
+ | |||
+ | == GET으로 입력받기 == | ||
+ | request.GET.get('name태그 이름') 형태로 GET으로 입력된 데이터를 받을 수 있다. | ||
+ | |||
− | |||
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' %}"> | ||
12번째 줄: | 17번째 줄: | ||
<p>최종적으로 받는 금액은 {{result}}야.</p> | <p>최종적으로 받는 금액은 {{result}}야.</p> | ||
</form> | </form> | ||
+ | </syntaxhighlight>view를 다음과 같이 작성한다.<syntaxhighlight lang="c#"> | ||
+ | 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) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | = POST로 입력받기 = | + | |
+ | == POST로 입력받기 == | ||
+ | |||
+ | = Form을 사용한 입력받기 = | ||
= 자료 검증 = | = 자료 검증 = | ||
그냥 받기만 해선 해당 자료로 연산할 때 에러가 뜨기도 한다. 이를 위해선 form을 사용한 검증이 되면 편하다. | 그냥 받기만 해선 해당 자료로 연산할 때 에러가 뜨기도 한다. 이를 위해선 form을 사용한 검증이 되면 편하다. | ||
[[분류:7-0. 장고 중급 튜토리얼]] | [[분류:7-0. 장고 중급 튜토리얼]] |
2021년 8월 20일 (금) 12:10 판
1 개요
장고에서 사용자로부터 데이터를 입력 받는 방법에 대해 살펴보자.
2 단순 입력받기
2.1 URL주소로 입력받기
2.2 GET으로 입력받기
request.GET.get('name태그 이름') 형태로 GET으로 입력된 데이터를 받을 수 있다.
HTML에서 form태그를 다음과 같이 작성한다.
<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='{{interest_rate}}' 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로 입력받기
3 Form을 사용한 입력받기
4 자료 검증
그냥 받기만 해선 해당 자료로 연산할 때 에러가 뜨기도 한다. 이를 위해선 form을 사용한 검증이 되면 편하다.