swordfish
swordfish

Reputation: 959

How to return html modal through jsonify in Flask using Markup?

I've created a function that contains a small modal window to return it in case of any error that the user makes when he submitting a form.

here is my modal_window.py:

# -*- coding: utf-8 -*-

from flask import Markup

def title():
    return Markup('''
    <div class=\"mw-narrow\" id=\"modal_window\"> <h3 class=\"mw_headline\">Fill in the title</h3> <a class=\"_c close_window\"> <i aria-hidden=true class=\"close_window_icon fa fa-times\" onclick=MWHide()></i> </a> <div class=\"mw_content\"> <p class=\"mw_descrip-mini text-center\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna</p><div class=\"pedit_row" style=\"margin-bottom: 0;\"> <span class=\"pedit_label\">The title</span> <input type=\"text" name=\"" placeholder=\"" class=\"pedit_labeled\"> </div></div><div class=\"mw_footer\"> <a class=\"flat_button-center" onClick=\"MWHide(); MWShow(\'edit-cphone\');\">change</a> </div></div>
    ''')

here is where i am returning the function in my views.py:

from .marks import title
if step == 'promotionCreate' and next_ == 'promotionType':

    title = request.form['title']

    if title is None:
        return jsonify({'error' : 'Title is important', 'field' : title})

If i tried to test it , i get an error that says:

raise TypeError(repr(o) + " is not JSON serializable")

Is there any way to return a modal window from my views and show it to the user.

Please if you have any ideas or how to make that work, help me .

Upvotes: 0

Views: 228

Answers (1)

Derlin
Derlin

Reputation: 9881

The form is a

MultiDict that implement all standard dictionary methods. Internally, it saves all values for a key as a list, but the standard dict access methods will only return the first value for a key (source)

I guess the title is not a string (you should try to log the result of type(title) to discover exactly the type), but a type that isn't serializable as is.

Two solutions:

  • use str(title) in your jsonify
  • use request.form.get(key, type=str) to automatically get a value of the proper type

Upvotes: 1

Related Questions