본문으로 바로가기

장고 폼(bound form, unbound form, cleaned_data, is_valid)

category 장고/MTV 2019. 1. 21. 16:29

폼 라이브러리


Widget

- <input type="text"> 또는 <textarea> 와 같이 HTML 폼 위젯에 대응되는 클래스, 위젯을 HTML 로 렌더링하는 것을 처리


Field

- 유효성 검증을 담당하는 클래스, 예를 들어 EmailField 는 데이터가 유효한 이메일 주소인지 확인


Form

- 그 자체에 대한 유효성 검증 규칙 및 HTML 로서의 표시 방법을 알고 있는 필드의 모음


Form Media(나중에 사용해볼 것)

- 폼을 렌더하기 위해 필요한 CSS 와 JavaScript 지원





바운드 폼(Bound Form)


- 바운드는 데이터 집합에 바인딩되어 있으면 해당 데이터의 유효성을 검사하고 HTML 로 표시된 데이터로 렌더링



언바운드 폼(Unbound Form)


- 언바운드 인 경우 유효성을 검사할 데이터가 없기 때문에 유효성 검사를 수행할 수 없지만 빈 양식을 렌더링




폼을 처리하기 위한 일반적인 패턴

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
        username = form.cleaned_data['username]
        password1 = form.cleaned_data['password1']
        password2 = form.cleaned_data['password2']
        return redirect('index')
    else:
        form = ContactForm()
        context = {
                'form': form,
        }
    return render(request, 'index.html', context)




form.is_valid()


데이터가 유효한지 아닌지를 검사

True/False 의 Boolean 값을 가짐


True 를 반환하는 바운드 폼

- 모든 폼에 데이터가 채워져 있기 때문에 True 를 반환

data = { 'subject': 'hello',
            'message': 'good morning',
            'sender': 'admin@example.com',
            'cc_myself': True,
             }
f = ContactForm(data)
f.is_valid()

>> True


False 를 반환하는 바운드 폼

- 모든 필드가 기본적으로 필요한 상태에서 제목을 공란으로 둘 경우, False 를 반환

data = { 'subject': '',
            'message': 'good morning',
            'sender': 'invalid email address',
            'cc_myself': True
            }
f = ContactForm(data)
f.is_valid()

>> False


Cleaned_data


Form 클래스의 각 필드는 데이터 유효성 검사뿐 아니라 일관된 형식으로 정규화하여 cleaning 하는 역할을 담당

cleaned_data 를 사용하면 특정 필드의 데이터를 다양한 방법으로 입력할 수 있으므로 항상 일관된 결과를 얻을 수 있다.



CharField, EmailField 와 같은 텍스트 기반 필드는 항상 입력을 유니 코드 문자열로 받는다

data = {'subject': 'hello',
            'message': 'good morning',
            'sender': 'admin@example.com',
            'cc_myself': True
           }

f = ContactForm(data)
f.is_valid()
# True
f.cleaned_data
# {'cc_myself': True, 'message': u'good morning', 'sender': admin@example.com', 'subject': u'hello'}


데이터 유효성( is_valid() )를 검사하지 않으면 Form 인스턴스에 cleaned_data 속성이 없다.

data = {'subject': 'hello',
            'message': 'good morning',
            'sender': 'admin@example.com',
            'cc_myself': True
           }
f = ContactForm(data)
f.is_valid()
# False
f.cleaned_data
Traceback (most recent call last):
...
AttributeError: 'ContactForm' object has no attribute 'cleaned_data'


cleaned_data 는 Form 의 안에서 정의한 필드에 값에 대해서만 리턴을 한다.

extra_field 는 cleaned_data 에 포함되지 않는다.

data = {'subject': 'hello',
            'message': 'good morning',
            'sender': 'admin@example.com',
            'cc_myself': True,
            'extra_field_1': 'foo',
            'extra_field_2': 'bar'
           }
f = Contactform(data)
f.is_valid()
# True
f.cleaned_data
# {'cc_myself': True, 'message': u'good morning', 'sender': u'admin@example.com', 'subject': u'hello'}


Form 에 정의된 모든 필드의 키와 값이 cleaned_data 에 포함된다.

nick_name 필드는 required=False 로 지정해도 cleaned_data 에 포함(빈 문자열)

class OptionalPersonForm(forms.ModelForm):
    first_name = CharField()
    last_name = CharField()
    nick_name = CharField(required=False)

data = {'first_name': u'Karl', 'last_name': u'Brian'}
f = OptionalPersonForm(data)
f.is_valid()
# True
f.cleaned_data
{'nick_name': u'', 'first_name': u'Karl', 'last_name': u'Brian'}



Form 을 HTML 로 출력


- form.as_p()

- form.as_ul()

- form.as_table()




참고자료:

* 이미 지난 버전의 자료이지만 이해를 하기 위한 관점으로 정리를 했습니다.


폼을 가지고 작업하기

The Forms API



'장고 > MTV' 카테고리의 다른 글

try, except 와 if else 를 써야할 때  (0) 2019.03.14
AbstractBaseUser 모델  (0) 2019.03.01
구문 분석 오류(could not parse ...)  (1) 2019.02.20
redirect 기능  (0) 2019.02.19
쿼리의 Q 모델을 활용한 검색 기능 구현  (0) 2019.02.06