Form클래스 사용하기
브라우저에서 정보를 입력하고 송신한 후에 잘못된 정보가 입력된 것을 알고 뒤로 가기를 하면 입력된 내용이 남아있어 편리하다고 느낀 경우가 있을 것이다. 이때를 위해 django에는 Form클래스가 존재한다.
forms.py 작성

from django import forms
class HelloForm(forms.Form):
name = forms.CharField(label='name')
mail = forms.CharField(label='mail')
age = forms.IntegerField(label='age')
django의 forms클래스를 계승하여 HelloForm클래스를 만들었다.
브라우저에서 입력받을 리스트를 name, mail, age로 추가.
텍스트인 경우엔 CharField, 숫자인 경우엔 IntegerField클래스를 사용.
hello/views.py 수정
from django.shortcuts import render
from django.http import HttpResponse
from .forms import HelloForm
def index(request):
params = {
'title':'Hello',
'message':'your data : ',
'form':HelloForm(),
}
if(request.method == 'POST'):
params['request'] = '이름 : ' + request.POST['name'] + '<br>이메일 : ' + request.POST['mail'] + '<br>연령 : ' + request.POST['age']
params['form'] = HelloForm(request.POST)
return render(request, 'hello/index.html', params)
param안에는 form이라는 값을 추가하여 HelloForm클래스의 인스턴스를 작성하여 전달하고 있다.
리퀘스트가 GET 혹은 POST인지를 확인하는 조건문을 작성.
GET, POST 간단한 설명
| GET | 준비되어 있는 데이터를 단지 사용하기 위한 처리 |
| POST | 새로운 데이터를 만들어서 받아들이는 처리 |
index.html 수정하여 HelloFrom을 표시
{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
</head>
<body class="container">
<h1 class="display-4 text-primary">{{title}}</h1>
<p class="h5 mt-4">{{message|safe}}</p>
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
{{ form }}
<input class="btn btn-primary" type="submit" value="click">
</form>
</body>
</html>
{{ form }}을 추가한다.
{{ message|safe }}의 |safe는 이스케이프 처리를 체크해준다. html태그가 그대로 표시되도록 해준다.
urlpatterns 수정
urlpatterns = [
path('', views.index, name='index'),
]
http://localhost:8000/hello/에서 확인.
위의 작업까지 끝나면 브라우저에서 필드를 확인할 수 있으나 모든 입력란이 옆으로 늘어서 있는 것을 볼 수 있다.
Form클래스에는 태그를 붙여 줄바꿈을 하여 좀 더 깔끔하게 정리할 수 있다.
| tr, td태그를 붙여준다. | |
| p태그를 붙여준다. | |
| <<Form>>.as_ul | ul태그를 붙여준다. |
index.html수정
form태그의 내용을 아래와 같이 수정한다.
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
{{ form.as_table }}
<input class="btn btn-primary" type="submit" value="click">
</form>
class HelloForm(forms.Form):
name = forms.CharField(label='name', widget=forms.TextInput(attrs={'class':'form-control'}))
mail = forms.CharField(label='mail', widget=forms.TextInput(attrs={'class':'form-control'}))
age = forms.IntegerField(label='age', widget=forms.NumberInput(attrs={'class':'form-control'}))
index.html 수정
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input class="btn btn-primary" type="submit" value="click">
</form>
html태그와 form클래스를 사용하는 것은 무슨 차이가 있을까?
간단히 말하면 form클래스를 사용하는 것이 클래스에 준비되어 있는 여러가지 기능을 손쉽게 사용할 수 있기 때문에 훨씬 편리하며 실제로도 자주 사용된다.
views함수를 클래스화하기
지금까지 views.py의 index함수에서 GET, POST처리를 해왔다. 하지만 두 개를 나누지 않으면 관리하기가 어렵다는 것은 금방 알 수 있다.
TemplateView클래스를 사용
hello/views.py 수정
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView
from .forms import HelloForm
class HelloView(TemplateView):
def __init__(self):
self.params = {
'title':'Hello',
'message':'your data: ',
'form':HelloForm(),
}
def get(self, request):
return render(request, 'hello/index.html', self.params)
def post(self, request):
msg = '당신은 <b>' + request.POST['name'] + '(' + request.POST['age'] + ')</b> 입니다. <br> 메일주소는 <b>' + request.POST['mail'] + '입니다. '
self.params['message'] = msg
self.params['form'] = HelloForm(request.POST)
return render(request, 'hello/index.html', self.params)
hello/urls.py 수정
from django.conf.urls import url
from .views import HelloView
urlpatterns = [
url(r'', HelloView.as_view(), name='index'),
]
클래스인가? 함수인가?
클래스의 최대 장점은 GET, POST 등의 HTTP메서드를 하나로 관리가 가능하다는 것.
여러 개의 애플리케이션이 공동으로 사용하고 싶은 경우에도 유용하다.
GET 뿐이라면 함수로 작성해도 충분.
'프로그래밍' 카테고리의 다른 글
| django chap3-1 모델과 데이터베이스 (0) | 2022.01.10 |
|---|---|
| django chap2-9 여러가지 필드 (0) | 2022.01.09 |
| django chap2-7 form송신 (0) | 2022.01.09 |
| django chap2-6 뷰 템플릿 (0) | 2022.01.08 |
| django chap2-5 뷰 템플릿 (0) | 2022.01.08 |