검색 폼 같은 경우는 GET 방식을 사용하여 북마크 등을 용이하게 함
폼클래스로 폼 생성 -> 뷰에서 폼클래스 처리 -> 폼 클래스를 템플릿으로 변환
폼 클래스는 모든 필드에 대해 유효성 검사를 실행하는 is_valid() 메소드를 내장하고 있다.
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
뷰에서 폼을 보여주기 위한 get 방식과 폼을 제출하기 위한 post 방식을 구현한다.
from django.shrtcuts import render
from django.http import HttpResponseRedirect
def get_name(request):
# post 요청 처리
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
# 폼 데이터가 유효하면, 데이터를 cleaned_data에 복사하고, '/thanks/'로 리다이렉트 함
new_name = form.cleaned_data['name']
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
# get 방식이거나 폼이 유효하지 않을 때, 'name.html' 템플릿으로 값은 비어 있고 필드만 생성되어 있는 폼 객체를 전달한다.
return render(request, 'name.html', {'form':form})
폼 객체를 템플릿에서 표현하는 방법은 이외에 3가지가 더 있다.
폼 객체는 필드만 전달하므로, <form> 요소와 <input type='submit'> 요소, 그외 기타 <table>, <ul> 등은 직접 작성 해야 한다.
<form action='/your_name/' method='post'>
{% csrf_token %}
{{ form }}
</form>
↓ 렌더링
<form action='/your_name/' method='post'>
<label for="your_name">Your name : </label>
<input id='your_name' type='text' name='your_name' maxlength='100'>
<input type='submit' value='Submit'>
</form>