3번째 줄: |
3번째 줄: |
| | | |
| = 단순 입력받기 = | | = 단순 입력받기 = |
| + | 간단하지만 그닥 권하지 않는다. 간단한 기능이라도 form을 통해 오류검사를 받는 편이 정신건강에 더 좋다. |
| | | |
| == URL주소로 입력받기 == | | == URL주소로 입력받기 == |
| | | |
| == 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> |
36번째 줄: |
38번째 줄: |
| | | |
| == POST로 입력받기 == | | == POST로 입력받기 == |
| + | GET과 동일하다. request.POST['name속성'] 혹은 request.POST.get('name속성') 형태로 전달받은 변수의 값들을 확인할 수 있다.(항상 문자열) |
| + | |
| + | form에서 method를 post로 바꿔주고, view에서 GET 대신 POST를 넣어주면 된다. |
| | | |
| = Form을 사용한 입력받기 = | | = 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> |
| + | |
| + | === 뷰 작성하기 === |
| + | 보통은 if함수로 <code>if request.method == 'POST':</code> 처럼 포스트 요청일때와 아닐 때를 구분하여 함수를 실행하는 게 일반적이다.<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을 사용한 검증이 되면 편하다.
| + | <syntaxhighlight lang="html+django"> |
| + | <form method="get" action="{% url 'utility:compound_interest' %}"> |
| + | {% csrf_token %} |
| + | {{form}} |
| + | <input type="submit" value="버튼에넣을말"> |
| + | </form> |
| + | </syntaxhighlight>위와 같이 작성할 수도 있지만, 에러메시지에 특화를 주고 싶거나, 속성마다 개별적인 HTML 코드를 부여하고 싶다면 다음과 같이 분리해 써넣을 수도 있다. |
| + | |
| + | 폼의 기능을 모두 활용하려면 폼 안에서 라벨을 지정하는 것과 html속성을 지정하는 방법을 사용하는 게 좋지만, 다음과 같은 형태는 백엔드와 프론트엔드를 분리할 수 있다는 장점이 있다.<syntaxhighlight lang="html+django"> |
| + | <!-----에러처리----------------------------> |
| + | {% if form.errors %} |
| + | <div class="alert alert-danger" role="alert"> |
| + | {% for field in form %}<!--모든 필드를 뒤지며 에러를 찾는다.--> |
| + | {% if field.errors %} |
| + | <strong>{{ field.label }}</strong><!--에러가 난 필드의 라벨에 굵음 처리--> |
| + | {{ field.errors }}<!--어떤 에러인지 보여준다.--> |
| + | {% endif %} |
| + | {% endfor %} |
| + | </div> |
| + | {% endif %} |
| + | |
| + | <form method="get" action="{% url 'utility:compound_interest' %}"> |
| + | {% csrf_token %} |
| + | <label for="principal">얼마 넣을래?</label> |
| + | <input type="text" name="principal" id="principal" |
| + | value="{{ form.principal.value|default_if_none:'' }}"> |
| + | <label for="interest_rate">이자율은?(단위는 %)</label> |
| + | <input type="text" name="interest_rate" id="interest_rate" |
| + | value="{{ form.interest_rate.value|default_if_none:'' }}">% |
| + | <label for="how_many">몇회 받아?</label> |
| + | <input type="text" name="how_many" id="how_many" |
| + | value="{{ form.how_many.value|default_if_none:'' }}"> |
| + | <label for="additional">중간에 일정금액 투입해?</label> |
| + | <input type="text" name="additional" id="additional" |
| + | value="{{ form.additional.value|default_if_none:'' }}"> |
| + | <p><input type="submit" value="Submit"></p> |
| + | <p>최종적으로 받는 금액은 {{result}}야.</p> |
| + | </form> |
| + | </syntaxhighlight> |
| [[분류:7-0. 장고 중급 튜토리얼]] | | [[분류:7-0. 장고 중급 튜토리얼]] |