티스토리 뷰

IT/Flask

[Flask] WTF (Flask-WTF)

Dragonz 2020. 9. 9. 12:23
반응형

 

Flask-WTF 를 사용하여 파이썬 스크립트에서 양식 필드를 정의하고 HTML 템플릿을 사용하여 렌더링 할 수 있다. WTF 필드에 유효성 검사를 적용할 수도 있다.

 

먼저 Flask-WTF 와 email_validator 패키지를 설치한다.

 

pip install flask-WTF
pip install email_validator

 

파일명 : forms.py

from flask_wtf import Form
from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField
from wtforms import validators, ValidationError

class ContactForm(Form) :
    name = TextField('Name of Student', [validators.DataRequired(), validators.Required('Please enter your name.')])
    gender = RadioField('Gender', choices = [('M', 'Male'),('F','Female')])
    address = TextAreaField('Address')
    email = TextField('Email', [validators.DataRequired(), validators.Required('Please enter your email address.'), validators.Email('Please enter your email address.')])
    age = IntegerField('Age')
    language = SelectField('Language', choices = [('cpp','c++'),('py','python')])
    submit = SubmitField('Send')

 

파일명 : 15_form_example.py

from flask import Flask, render_template, request, flash
from forms import ContactForm
app = Flask(__name__)
app.secret_key = 'development key'

@app.route('/contact', methods = ['GET', 'POST'])
def contact() :
    form = ContactForm()

    if request.method == 'POST' :
        if form.validate() == False :
            flash('All fields are required.')
            return render_template('15_contact.html', form = form)
        else :
            return render_template('15_success.html')
    elif request.method == 'GET' :
        return render_template('15_contact.html', form = form)

if __name__ == '__main__' :
    app.run(debug=True)

forms.py 에서 정의한 ContactForm() 클래스에서 양식필드를 정의하고, 정의된 내용을 15_contact.html 로 전달한다.

 

파일명 : 15_contact.html

<!doctype html>
<html>
    <body>
        <h2 style = "text-align:center">Contact Form</h2>

        {% for message in form.name.errors %}
        <div>{{ message }}</div>
        {% endfor %}

        {% for message in form.email.errors %}
        <div>{{ message }}</div>
        {% endfor %}

        <form action = 'http://localhost:5000/contact', method = post>
            <fieldset>
                <legend>Contact Form</legend>
                {{ form.hidden_tag() }}

                <div style = font-size:20px; font-weight:bold; margin-left:150px;>
                    {{ form.name.label }}<br>
                    {{ form.name }}<br>

                    {{ form.gender.label }}
                    {{ form.gender }}
                    {{ form.address.label }}<br>
                    {{ form.address }}<br>

                    {{ form.email.label }}<br>
                    {{ form.email }}<br>

                    {{ form.age.label }}<br>
                    {{ form.age }}<br>

                    {{ form.language.label }}<br>
                    {{ form.language }}<br>

                    {{ form.submit }}
                </div>
            </fieldset>
        </form>
    </body>
</html>

validation 결과 문제가 있으면 웹페이지 상단에 flash 메세지 형태로 검증결과를 출력한다.

 

파일명 : 15_success.html

<!doctype html>
<html>
    <body>
        <h2>Form posted successfully</h2>
    </body>
</html>

 

첫 화면

 

email 항목이 공란인 경우 validation 체크에 의해 입력란을 작성하라는 메세지가 출력된다

 

입력한 email 이 형식에 맞지 않으면 validation 체크에 의해 falsh 메세지 형태로 브라우저 상단에 검증내용이 출력된다

 

전체 항목 입력

 

성공 메세지 출력

 

END

반응형

'IT > Flask' 카테고리의 다른 글

[Flask] SQLAlchemy  (0) 2020.09.09
[Flask] SQLite3  (0) 2020.09.09
[Flask] 메일발송 (Mail)  (0) 2020.09.05
[Flask] 파일 업로딩 (File Uploading)  (0) 2020.08.26
[Flask] 메세지 플래싱 (Message Flashing)  (0) 2020.08.14
댓글
공지사항