Coder Social home page Coder Social logo

flask-modals's Introduction

Modals for Flask

Use forms in Bootstrap modals with Flask.

Description

Plain forms can be boring. Using them in modals is possible, but requires JavaScript. Normal form submission in modals is problematic.

This Flask extension eases the process of using forms in Bootstrap modals. Bootstrap versions 4 and 5 are supported. No JavaScript coding is required on your part. You can code in pure Python - flashing messages and rendering templates.

Installation

pip install Flask-Modals

Setup

  1. Import the Modal class and instantiate it in your app.py file.

    from flask_modals import Modal
    
    app = Flask(__name__)
    modal = Modal(app)

    You will also need a secret key in the app config (not shown).

  2. Alternatively if you are using the application factory pattern:

    from flask_modals import Modal
    
    modal = Modal()
    
    def create_app():
        app = Flask(__name__)
        modal.init_app(app)

  3. Include the following in the head tag of your base template.

    {{ modals() }}

  4. Include the following in the modal body.

    <div class="modal-body">
    {{ modal_messages() }}
    <form method="post">
    ...

Basic usage

You only need to import the function render_template_modal in your routes.py file. Use it instead of render_template in the route handler for the page with the modal form. It takes an extra argument - modal (the modal id with a default of modal-form).
The extension works by submitting the modal form twice - first via ajax and then, if all validations pass, normally. When submiited via ajax, it passes a field '_ajax' with the form, which can be used as shown below.

Example route handler:

from flask_modals import render_template_modal

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

    ajax = '_ajax' in request.form  # Add this line
    form = LoginForm()
    if form.validate_on_submit():
        if form.username.data != 'test' or form.password.data != 'pass':
            flash('Invalid username or password', 'danger')
            return redirect(url_for('index'))

        if ajax:        # Add these
            return ''   # two lines
        login_user(user, remember=form.remember_me.data)

        flash('You have logged in!', 'success')
        return redirect(url_for('home'))

    # Add this line
    return render_template_modal('index.html', form=form)

Other usage

If you want to render a template and not redirect:

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

    ajax = '_ajax' in request.form
    form = LoginForm()
    if form.validate_on_submit():
        if form.username.data != 'test' or form.password.data != 'pass':
            flash('Invalid username or password', 'danger')
            return render_template_modal('index.html', form=form)

        if ajax:
            return ''
        login_user(user, remember=form.remember_me.data)

        flash('You have logged in!', 'success')
        return render_template_modal('index.html', form=form)

    return render_template_modal('index.html', form=form)

If the above looks verbose, you can use the response decorator and return a context dictionary, like so:

from flask_modals import response

@app.route('/', methods=['GET', 'POST'])
@response('index.html')
def index():
    ...
    ...
    return {'form': form}

Note

  1. See the examples folder in the repo for more details.

  2. The extension loads the NProgress js library to display a progress bar during form submission.

flask-modals's People

Contributors

deb17 avatar emmett08 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.