SW/Python

[Flask] Templates 사용법3

17Hyuk 2022. 5. 1. 17:09

app.py

from flask import Flask, render_template, flash
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

# StringField : text박스
# SubmitField : submit 버튼
# DataRequired : 유효성검사

app = Flask(__name__)
app.config['SECRET_KEY'] = "super secret"   #보안용

# Form 생성
class NameForm(FlaskForm):
    form_name = StringField('이름라벨', validators=[DataRequired()])    #validators에 의해서 값이 없으면 안됨
    form_submit = SubmitField('제출라벨')



@app.route('/')
def index():
    name = '혁'
    hobbys = ['수영', '자전거']
    return render_template('index.html',
    index_name = name,
    index_hobbys = hobbys
    )

#유저추가
@app.route('/new_user/', methods=['GET', 'POST'])
def new_user():
    name = None
    Naemform = NameForm()

    if Naemform.validate_on_submit():
        name = Naemform.form_name.data
        flash('전송성공')


    return render_template('new_user.html',
    html_name = name,
    html_form = Naemform
    )


#요청한 페이지를 찾을 수 없음
@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404


app.run(host='0.0.0.0', port=5000, debug=True)

 

base.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>template연습</title>
    </head>
    <body>        
        <a href="{{ url_for('index') }}"><h1>template연습(홈으로)</h1></a>
        <a href="{{ url_for('new_user') }}"><h1>새로운유저</h1></a>
        <hr>
        <br>
        {% block content %}
        {% endblock %}
    </body>
</html>

 

404.html

{% extends 'base.html' %}

{% block content %}

    <h1>404 Error</h1>
    <p>요청한 페이지가 없습니다.</p>

{% endblock %}

 

new_user.html

{% extends 'base.html' %}

{% block content %}

    {% for message in get_flashed_messages() %}
        {{ message }}
    {% endfor %}




    {% if html_name != None %}
        <h2>Hello {{html_name}}</h2>
    {% else %}
        <h2>이름은?</h2>
        <form method="post">
            {{ html_form.hidden_tag() }}

            {{ html_form.form_name.label }}
            {{ html_form.form_name() }}
            <br>
            {{ html_form.form_submit.label }}
            {{ html_form.form_submit() }}
        </form>
    {% endif %}

 

설명

flash를 사용하기 위해서는 'SECRET_KEY'를 사용해야 된다.

값은 아무거나 입력하면 된다.

 

Form을 만들어주기 위해서 class를 생성해줬다.

그 후 NameForm=NameForm()을 통해서 그 클래스를 할당해줬다.

html_form=NameForm을 통해서 new_user.html에서 사용할 수 있도록 했다.

html_form.hidden_tag()는 보안을 위한 것 이다.

html_form.form_name()을 통해서 class 값을 접근 했다.

 

submit시 message를 출력하는 코드이다.