Formuláre

Formuláre je najľahšie urobiť pomocou flask-wtf. Nainštalujeme si ho a importujeme.

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

Budeme pracovať na vyhľadávacom mechanizme v našom playliste. Vytvoríme si teda nový formulár pomocou tried:

class SearchForm(FlaskForm):
    search = StringField('', validators=[DataRequired()])
    submit = SubmitField("Hľadaj")

    class Meta:
        csrf = False

A v prípade, že sa niečo vo formulári odoslalo, vyfiltrujeme výsledok pomocou danej frázy (vo funkcii playlist()):

    form = SearchForm()
    try:
        search_phrase = request.form["search"].lower()
        if form.validate_on_submit():
            filtered_songs = [song for song in render_songs if (search_phrase in song['title'].lower()) or (search_phrase in song['artist'].lower())]
            return render_template('index.html', name="songy obsahujúce '" + search_phrase + "'", songs=filtered_songs, form=form, search=True)
        else:
            return render_template('index.html', name="Dobré texty", songs=render_songs, form=form)
    except:
        return render_template('index.html', name="Dobré texty", songs=render_songs, form=form)

Už si len upravím našu šablónu.

  {% include 'search.html' %}
  <h1>Môj playlist - {{ name }}</h1>
  {% if not search %}
    <a href="{{ url_for('playlist') }}">Základné zoradenie</a><br/>
    <a href="{{ url_for('playlist', sorting='artist') }}">Zoraď abecedne podľa umelca</a><br/>
    <a href="{{ url_for('playlist', sorting='title') }}">Zoraď abecedne podľa názvu pesničky</a><br/>
  {% endif %}

a vytvoríme search.html

<form method="POST" action="">
    {{ form.search.label }} {{ form.search(size=20) }}
    {{ form.submit() }}
</form>

results matching ""

    No results matching ""