티스토리 뷰
반응형
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>
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 |
댓글
공지사항