Code Monkey home page Code Monkey logo

bootstrap-flask's Introduction

Bootstrap-Flask

PyPI - License Current version on PyPI Build status Coverage Status Open Collective

Bootstrap-Flask is a collection of Jinja macros for Bootstrap 4 & 5 and Flask. It helps you to render Flask-related data and objects to Bootstrap markup HTML more easily:

  • Render Flask-WTF/WTForms form object to Bootstrap Form.
  • Render data objects (dict or class objects) to Bootstrap Table.
  • Render Flask-SQLAlchemy Pagination object to Bootstrap Pagination.
  • etc.

Installation

$ pip install -U bootstrap-flask

Example

Register the extension:

from flask import Flask
# To follow the naming rule of Flask extension, although
# this project's name is Bootstrap-Flask, the actual package
# installed is named `flask_bootstrap`.
from flask_bootstrap import Bootstrap5

app = Flask(__name__)
bootstrap = Bootstrap5(app)

Assuming you have a Flask-WTF form like this:

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 150)])
    remember = BooleanField('Remember me')
    submit = SubmitField()

Now with the render_form macro:

{% from 'bootstrap5/form.html' import render_form %}
<html>
<head>
<!-- Bootstrap CSS -->
</head>
<body>

<h2>Login</h2>
{{ render_form(form) }}

<!-- Bootstrap JS -->
</body>
</html>

You will get a form like this with only one line code (i.e. {{ render_form(form) }}):

form rendering

When the validation fails, the error messages will be rendered with proper style:

error form rendering

Read the Basic Usage docs for more details.

Live demo

https://bootstrap-flask-example.azurewebsites.net/

Donate

If you find Bootstrap-Flask useful, please consider donating today. Your donation keeps Bootstrap-Flask maintained and updated with Bootstrap.

Links

Notes for Bootstrap 4 & 5 support

The Bootstrap 5 support is added in Bootstrap-Flask 2.0 version. Now you can use the separate extension class for different Bootstrap major versions.

For Bootstrap 4, use the Bootstrap4 class:

from flask_bootstrap import Bootstrap4

# ...
bootstrap = Bootstrap4(app)

and import macros from the template path bootstrap4/:

{% from 'bootstrap4/form.html' import render_form %}

For Bootstrap 5, use the Bootstrap5 class:

from flask_bootstrap import Bootstrap5

# ...
bootstrap = Bootstrap5(app)

and import macros from the template path bootstrap5/:

{% from 'bootstrap5/form.html' import render_form %}

The Bootstrap class and bootstrap/ template path are deprecated since 2.0 and will be removed in 3.0.

Migration from Flask-Bootstrap

If you come from Flask-Bootstrap, check out this tutorial on how to migrate to this extension.

Contributing

For guidance on setting up a development environment and how to make a contribution to Bootstrap-Flask, see the development documentation and Flask's contributing guidelines.

License

This project is licensed under the MIT License (see the LICENSE file for details). Some macros were part of Flask-Bootstrap and were modified under the terms of its BSD License.

bootstrap-flask's People

Contributors

180909 avatar a2yp avatar bennye avatar burhanharoon avatar caffeinatedmike avatar chug2k avatar cthoyt avatar davidlesieur avatar demetriex avatar dosenpfand avatar e2jk avatar etiennepelletier avatar greyli avatar guidoiaquinti avatar jugmac00 avatar meizhaohui avatar michaelbukachi avatar msoucy avatar muxuezi avatar mvhconsult avatar neil-s avatar nickovs avatar nuno-andre avatar ogabrielluiz avatar pandermusubi avatar titaniumhocker avatar valr avatar yuxiaoy1 avatar zacheryfaria avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bootstrap-flask's Issues

Custom validation didn't display properly

你好!
I'm using Bootstrap-Flask to render a registration form, but the custom message for the DataRequired() validator still show up as the default message. It shows as excepted in password2, I guess it's because of EqualTo. My forms.py:

# app/auth/forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Regexp, Email, Length, EqualTo


class RegistrationForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(message='请输入用户名'), Regexp('^[A-Za-z][A-Za-z0-9_.]*$',
                                                                                     0, '用户名只能包含字母,数字,点'
                                                                                        '或下划线'), Length(1, 64)])
    email = StringField('邮箱', validators=[DataRequired(message='请输入邮箱'), Email(message='请输入真实的邮箱地址')])
    password = PasswordField('密码', validators=[DataRequired(message='请输入密码')])
    password2 = PasswordField('确认密码', validators=[DataRequired(message='请输入确认密码'), EqualTo('password',
                                                                                           message='密码不一致')])
    submit = SubmitField('注册')

Any ideas for this problem? Thanks!

no example about button_map dictionary in the render_field macro

Hi,Greyli:
I am try to use the new Bootstrap-flask to build my website. And try to understand to examples.
when I read the render_field(field, form_type="basic", horizontal_columns=('lg', 2, 10), button_map={}) part. I try to use the form.html example to check the method.
There are four render_field in the example. I try to add the button_map={} into the render_field.
{{ render_field(form.username) }}
{{ render_field(form.password) }}
{{ render_field(form.remember) }}
{{ render_field(form.submit) }}

for example:
{{ render_field(form.submit, button_map={form.submit:'success'}) }} --> not work!
{{ render_field(form.submit, button_map={'form.submit':'success'}) }} --> not work!
{{ render_field(form.submit, button_map={'submit':'success'}) }} --> work!!!
{{ render_field(form.submit, button_map={'submit':'danger'}) }} --> work!!!
{{ render_field(form.submit, button_map={'submit':'info'}) }} --> work!!!
{{ render_field(form.submit, button_map={'submit':'primary'}) }} --> work!!!

Then I think,we should add the example how to make the button_map mapping dictionary in the docs.

If I change class HelloForm(FlaskForm) in the app file submit = SubmitField() to upload = SubmitField(), Then if the form.html should change the render_field method .
{{ render_field(form.submit, button_map={'submit':'primary'}) }} will change to {{ render_field(form.upload, button_map={'upload':'primary'}) }}.

Then it will work. I suggest to add this example. Thanks.

New feature plan: Bootstrap a Flask project template

Just like cookiecutter-flask, add a CLI system to support bootstrap (verb, not the "Bootstrap") a Flask project template.

For example, bootstrap a small app, use an src folder, use Bootstrap 4:

$ bootstrap-flask -s --src --bs4

How can I add custom colors to navbar?

Hello, i've been trying to change the colors of the navbar, other than "navbar-light" or "navbar-dark". I want to make it from any color.

I tried in several ways to use a base.css in a static folder, but I can't make it work. Is there a step by step guide to achieve this? I feel like the docs is not enough and it's needed an example of a custom widget.

New feature plan: Support Bootstrap 3

I will try to add a unified API to support both Bootstrap 3 and Bootstrap 4, that's mean you will only need to set a configuration variable to change the Bootstrap main version:

app.config['BOOTSTRAP_MAIN_VERSION'] = 3

Then the helper functions and macros will render HTML with correct Bootstrap version:

{% from "bootstrap/form.html" import render_form %}

{% render_form(form) %}  {# render a Bootstrap 3 form now #}

Any idea on config var naming and macro API designing is welcome.

render_field enchancements

It would be great if the render_field method allowed for other keywords to be passed in as parameters.

For example, it would be great to provide keywords such as:

  • placeholder
  • aria-describedby

etc

Furthermore, an option to not generate a label for the field would be great too (relates to #47)

Any plans to add a macro for Flashed Messages?

Hey Greyli, thanks for taking over development and actively maintaining a Bootstrap 4 package for Flask!

The original flask-bootstrap had a utility function for rendering flashed messages. Are you planning on adding this as well? Will make the transition over to your package easier.

Form doesn't work on example

I installed the example as directed in the documentation. When I run the Form example I get the error:

jinja2.exceptions.UndefinedError: the template 'bootstrap/form.html' (imported on line 2 in 'form.html') does not export the requested name 'render_form_row'_**

Everything else in the example appears to work.

pipenv install bootstrap-flask return unknown location

Im using pipenv to manage my python modules,
after i ran :
pipenv install bootstrap-flask

this error raised

flask.cli.NoAppException: While importing "main", an ImportError was raised:

Traceback (most recent call last):
  File "...../lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
    __import__(module_name)
  File ".../main.py", line 1, in <module>
    from app import app, db
  File ".../app/__init__.py", line 7, in <module>
    from flask_bootstrap import Bootstrap
ImportError: cannot import name 'Bootstrap' from 'flask_bootstrap' (unknown location)

I tried to install bootstrap-flask in my global env, with 'exit' current env, and doing
python3 -m pip install bootstrap-flask
same result .

Please advise, thank you

jQuery sources aren't fetched

With the default load_js macro, the URL that gets rendered doesn't match any sources shipped by this project - although the versioned file exists, it looks for the simply-named minified javascript:

screen shot 2018-08-06 at 10 23 29 pm

Seems like either constructing the versioned jquery file or copying/linking the versioned jquery minified source into the unversioned path would work.

1.3.0 adding an extra space to form field class attribute

After updating to 1.3.0 I started getting the following JS error on one of my forms.

jQuery.Deferred exception: An invalid or illegal string was specified create/<@http://localhost:5000/_static/libs/filepond-4-7-2/filepond.min.js:9:87915 create@http://localhost:5000/_static/libs/filepond-4-7-2/filepond.min.js:9:87875 D/<@http://localhost:5000/_static/libs/filepond-4-7-2/filepond.min.js:9:9772 Pr@http://localhost:5000/_static/libs/filepond-4-7-2/filepond.min.js:9:92198 Mr@http://localhost:5000/_static/libs/filepond-4-7-2/filepond.min.js:9:97464 Cr/<@http://localhost:5000/_static/libs/filepond-4-7-2/filepond.min.js:9:98908 Cr@http://localhost:5000/_static/libs/filepond-4-7-2/filepond.min.js:9:99006 e.create@http://localhost:5000/_static/libs/filepond-4-7-2/filepond.min.js:9:102387 @http://localhost:5000/_static/sdist/67435b6aa6ce2cf0e35dd319fb7967e9.js:2:402 l@http://localhost:5000/_static/js/libs/jquery-3.3.0.min.js:2:29375 a/</c<@http://localhost:5000/_static/js/libs/jquery-3.3.0.min.js:2:29677

I traced this down to the upgrade from 1.2.0 to 1.3.0

The diff was...

<input class="form-control-file " id="file_" name="file_" type="file"> with 1.3.0
<input class="form-control-file" id="file_" name="file_" type="file"> with 1.2.0

Notice the extra space.

I was able to workaround the issue by adding render_kw={"class": "xyz"} to my form class.

cannot import name 'Bootstrap' from 'flask_bootstrap'

I'm having trouble using bootsrap-flask
using pip freeze I know that I have "Bootstrap-Flask==1.1.0" installed.
Here's my code:

from flask import Flask
from flask_bootstrap import Bootstrap
# ...

bootstrap = Bootstrap()
# ...
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    bootstrap.init_app(app)
    # ...
    
    return app

And yet, I'm getting the error "cannot import name 'Bootstrap' from 'flask_bootstrap
". Anyone know why?

分页bug?还是我错了?

源码:

https://github.com/wedojava/exloger

情景:

我在index页有一个form表单,提交email和IP信息进行查询,并将查询结果在index页展示。

问题:

我把提交的email和IP放到session里,分别是 session['email']session['ip']。点击页码的时候,再次查询这两个关键字段,并将结果集分页。但此时点分页的会报错 404。

简单点说,index 里提交表单能查询出结果,并且分页了,但是点击某个页面的时候 index.,会报错404。

错误位置:

routes.py 的 elif 里:

l = LogImported.query.filter(rule)
pagination = l.paginate(page, per_page=50, error_out=True)

我发现这里 l = LogImported.query.filter(rule) 的类型是对的,第二行就错了。 if 里能查询出结果并展示,但是 elif 里不能出结果。调用的 rule 的内容一模一样,问题出哪里了呢?求解答。

主要代码:

routes.py:

@bp.before_app_request
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()
    
    session['email'] = session['email'] if session['email'] else '[email protected]'
    session['ip'] = session['ip'] if session['ip'] else '127.0.0.1'

@bp.route('/', methods=['GET', 'POST'])
@bp.route('/index', methods=['GET', 'POST'])
def index():
    form = SearchForm()
    page = request.args.get('page', 1, type=int)
    if form.validate_on_submit():
        words_email = ["%" + form.email.data + "%"]
        rule_sender = and_(*[LogImported.sender_address.like(w) for w in words_email])
        rule_recipient = and_(*[LogImported.recipient_address.like(w) for w in words_email])
        rule_return = and_(*[LogImported.return_path.like(w) for w in words_email])
        rule_email = rule_sender + rule_recipient + rule_return
        words_ip = ["%" + form.ip.data + "%"]
        rule_client_ip = and_(*[LogImported.client_ip.like(w) for w in words_ip])
        rule_server_ip = and_(*[LogImported.server_ip.like(w) for w in words_ip])
        rule_original_client_ip = and_(*[LogImported.original_client_ip.like(w) for w in words_ip])
        rule_original_server_ip = and_(*[LogImported.original_server_ip.like(w) for w in words_ip])
        rule_ip = rule_client_ip + rule_server_ip + rule_original_client_ip + rule_original_server_ip
        rule = rule_email + rule_ip
        l = LogImported.query.filter(rule)
        pagination = l.paginate(page, per_page=50, error_out=True)
        pageitems = pagination.items
        session['email'] = form.email.data
        session['ip'] = form.ip.data
        return render_template('index.html', title=_('Home'), form=form, loglist = l, \
        pageitems = pageitems, pagination = pagination)
    elif session['email'] is not '[email protected]':
        words_email = ["%" + session['email'] + "%"]
        rule_sender = and_(*[LogImported.sender_address.like(w) for w in words_email])
        rule_recipient = and_(*[LogImported.recipient_address.like(w) for w in words_email])
        rule_return = and_(*[LogImported.return_path.like(w) for w in words_email])
        rule_email = rule_sender + rule_recipient + rule_return
        words_ip = ["%" + session['ip'] + "%"]
        rule_client_ip = and_(*[LogImported.client_ip.like(w) for w in words_ip])
        rule_server_ip = and_(*[LogImported.server_ip.like(w) for w in words_ip])
        rule_original_client_ip = and_(*[LogImported.original_client_ip.like(w) for w in words_ip])
        rule_original_server_ip = and_(*[LogImported.original_server_ip.like(w) for w in words_ip])
        rule_ip = rule_client_ip + rule_server_ip + rule_original_client_ip + rule_original_server_ip
        rule = rule_email + rule_ip
        l = LogImported.query.filter(rule)
        pagination = l.paginate(page, per_page=50, error_out=True)
        pageitems = pagination.items
        return render_template('index.html', title=_('Home'), form=form, loglist = l, \
        pageitems = pageitems, pagination = pagination)
    else:
        return render_template('index.html', title=_('Home'), form=form)

forms.py:

class SearchForm(FlaskForm):
    email = StringField(_l('Email'))
    ip = StringField('IP', validators=[Length(min=0, max=140)])
    submit = SubmitField(_l('Submit'))

init.py:

from flask import Blueprint

bp = Blueprint('main', __name__)

from app.main import routes

models.py:

class LogImported(db.Model):
    id = db.Column(db.Integer, index=True, primary_key=True)
    date = db.Column(db.DateTime, default=datetime.utcnow)
    sender_address = db.Column(db.String(255), index=True)
    recipient_address = db.Column(db.String(255))
    recipient_count = db.Column(db.Integer)
    return_path = db.Column(db.String(255))
    client_hostname = db.Column(db.String(255))
    client_ip = db.Column(db.String(100))
    server_hostname = db.Column(db.String(255))
    server_ip = db.Column(db.String(100))
    original_client_ip = db.Column(db.String(100))
    original_server_ip = db.Column(db.String(100))
    event_id = db.Column(db.String(50))
    total_bytes = db.Column(db.Integer)
    connector_id = db.Column(db.String(50))
    message_subject = db.Column(db.String(255))
    source = db.Column(db.String(50))

Update to Bootstrap 4.3?

Do you plan to update to Bootstrap 4.3 soon or would you accept a PR with such an update?
Regards

SQLALCHEMY startup issues

Tried starting bootstrap-flask just now and saw these warnings pop up:

.../site-packages/flask_sqlalchemy/init.py:814: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
.../init.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '

Am also getting some test warnings with Python 3.7.3.

.../usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py:615: ResourceWarning: unclosed file <_io.BufferedReader name='../web/bootstrap-flask-test2/flask_bootstrap/static/css/bootstrap.min.css'>
testMethod()
ResourceWarning: Enable tracemalloc to get the object allocation traceback
/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py:615: ResourceWarning: unclosed file <_io.BufferedReader name='../web/bootstrap-flask-test2/flask_bootstrap/static/js/bootstrap.min.js'>
testMethod()
ResourceWarning: Enable tracemalloc to get the object allocation traceback
/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py:615: ResourceWarning: unclosed file <_io.BufferedReader name='../web/bootstrap-flask-test2/flask_bootstrap/static/jquery.min.js'>
testMethod()
ResourceWarning: Enable tracemalloc to get the object allocation traceback
............


Ran 16 tests in 0.588s

OK

There doesn't seem to be any explanation about this in the docs. Please advise.

Todo (PR welcome)

Done

  • Host a live demo of the example application.
  • Improve render_icon to use CSS icon (Is it needed? The current implementation is using SVG sprite).
  • Improve the display of table action buttons (the delete icon is not in line with others).
  • Add warning if Flask-WTF not installed when using render_table actions.
  • Support to add custom action button.
  • Move builds to GitHub Action.
  • Add render test for every input and form type.
  • Add doc for configuration options.
  • Add config var to set default form submit button class: size, style, outline, etc. Maybe use BOOTSTRAP_FORM_BTN_SIZE, BOOTSTRAP_FORM_BTN_STYLE, BOOTSTRAP_FORM_BTN_OUTLINE, BOOTSTRAP_FORM_BTN_BLOCK.

Don't include newlines at end of string

  <head>
  {%- block head %}
    <title>{% block title %}{{title|default}}{% endblock title %}</title>
    {%- block metas -%}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {%- endblock metas %}
    {%- block styles -%}
    <!-- Bootstrap -->
    {{ bootstrap.load_css() }}
    {%- endblock styles %}
  {% endblock head -%}
  </head>

Since bootstrap.load_css() outputs a newline '\n' at the end of the returned string, In order to get spacing right on the rendered source, you have to remove a newline somewhere else in the template which makes it look off.

  <head>
  {%- block head %}
    <title>{% block title %}{{title|default}}{% endblock title %}</title>
    {%- block metas -%}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {%- endblock metas %}
    {%- block styles -%}
    <!-- Bootstrap -->
    {{ bootstrap.load_css() }}
    {%- endblock styles %}  {% endblock head -%}
  </head>

Please Vote: Macro name for flashed messages

I'm trying to implement a macro to render flashed messages, based on #5, which name do you think is best:

  • 🎉 render_message
  • ❤️ render_messages
  • 🚀 render_flash_message
  • 👀 render_flashed_messages

Thanks for voting!

Bootstrap requires Popper.js

When using bootstrap.load_js(), the popper script is included after bootstrap, ending with

Bootstrap requires Popper.js

when using dropdowns, etc. A simple fix is to change the order of Markup in the last line of __init__.py:

# render popper before js
return Markup('%s\n%s\n%s\n' % (jquery, popper, js))

Support to not displaying labels for form inputs

When a WTForms field has no label, a label is generated from the variable name it is assigned to, e.g. for a TextAreaWidget. This is very useful (convention over configuration).

However, in certain cases, the label of an input is not added to thre resulting HTML. What parameter can be used when creating a WTForm field in order to extend the form template here to not add the label around an input?

This relates to:

Support clipboardjs

Made an implementation which supports clipboardjs by subclassing SubmitField as ClipboardField, passing three extra input parameters. I've extended the form.html template to render it and it works.

In the app code:

class ClipboardField(SubmitField):
    def __init__(self, label=None, cb_value='', cb_cut=False, cb_text=False, **kwargs):
        super(ClipboardField, self).__init__(label, **kwargs)
        self.cb_value = cb_value
        self.cb_cut = cb_cut
        self.cb_text = cb_text

class SortForm(FlaskForm):
    copy = ClipboardField('Kopieer', cb_value='words')
    cut = ClipboardField('Knip', cb_value='words', cb_cut=True)
    words = TextAreaField(default='aaa\nbbb)

In form.html:

...
    {%- elif field.type == 'ClipboardField' -%}
        {# deal with jinja scoping issues? #}
        {% set field_kwargs = kwargs %}

        {# note: same issue as above - should check widget, not field type #}
        {% call _hz_form_wrap(horizontal_columns, form_type, True, required=required) %}
            {# TODO support field_kw_args or implement by overriding field() #}
            <button class="btn btn-{{ button_map.get(field.name, 'light') }}"{% if field.cb_cut %} data-clipboard-action="cut"{% endif %} data-clipboard-{% if field.cb_text %}text="{{ field.cb_value|safe }}"{% else %}target="#{{ field.cb_value|safe }}"{% endif %}>{{ field.label.text|safe }}</button>
        {% endcall %}
    {%- elif field.type == 'SubmitField' -%}
...

It does require the following two lines to be added to the user template

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script type="text/javascript">new ClipboardJS('.btn');</script>

What is a better way to implement this in bootstrap-flask so it is added behind the scenes?

flask_bootstrap.Bootstrap object' has no attribute 'load_css'

您好,没提过issue,不知道有没有走错地方,打扰了。
就是这个bootstrap-flask在自己的电脑里用得挺好的,但一挂到服务器上就报错。我把问题在stackoverflow上提了,好像没人理我。过会儿到其他两个平台再问问。
因为是小白,想快速搭好一个好看点的网站,所以用了flask-bootstrap,现在卡死在这里了:)

希望能够帮忙解答一下,谢谢!

It seemed that render_kw in render_form is not working on the "class" property.

https://github.com/greyli/bootstrap-flask/blob/9ca1e7f0a2d3233d781f23da23ad919901a09183/flask_bootstrap/templates/bootstrap/form.html#L235

My code here:

class RegistrationForm(FlaskForm):
    submit = SubmitField('Register', render_kw={'class': 'btn-primary'})
{% from 'bootstrap/form.html' import render_form %}

{{ render_form(form) }}

The return is quite confusing:

<input class="btn btn-secondary" id="submit" name="submit" type="submit" value="Register">

And it seemed that render_form is not passing the render_kw of the SubmitField to the rendered html. This made me confused.

Add render_modal macro

Add macro to render Bootstrap modal:

{% from 'bootstrap/utils.html' import render_modal %}

{{ render_modal(id='deleteConfirm', title='Warning', body='Are you sure?', close_btn=('secondary', 'Close'), confirm_btn('primary', 'Confirm')) }}

will output:

<div class="modal fade" id="deleteConfirm" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Warning</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        Are you sure?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Confirm</button>
      </div>
    </div>
  </div>
</div>

I have problem with this app, i got TemplateNotFound: base.html

sorry bother you guys:

I just did example code like yours, but i get a exception with TemplateNotFound: base.html.

I have to uninstall Bootstrap-Flask, and install flask-bootstrap, then it works for me, i dont know why this happen, can you fix it, thank you

PLEASE VOTE: Change the default style of form button to btn-primary

In Bootstrap 3, there is a default button style btn-default, but it's removed in Bootstrap 4. Then I use btn-secondary in this project as a default button style, now I am wondering maybe btn-primary is a better choice? What do you think?

You can just vote for your choice, thanks!

🚀 btn-primary (the blue one)
👀 btn-secondary (the grey one)

image

Form validation feedback doesn't show

I'm using a form auto generated with the bootstrap/form.html macros like that:

{{ bf4.render_form(forgot_password_form, action=url_for_security('forgot_password'), render_kw={'name': "reset_password_form"}, horizontal_columns=('lg', 3, 5), form_type='horizontal', button_map={'submit': 'success'}) }}

But when the server returns an error, the form does get the feedback:

<form action="/reset" method="post" class="form" role="form" name="reset_password_form">
        <input id="csrf_token" name="csrf_token" type="hidden" value="xxx">
    <div class="form-group row required">
                <label class="form-control-label  col-lg-3" for="email">Adresse email</label>
                <div class=" col-lg-5">
                    <input class="form-control is-invalid" id="email" name="email" required="" type="text" value="xxx" style="background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 16px; background-position: calc(100% - 4px) 50%; background-image: url(&quot;moz-extension://e62d5f8c-1e48-4df9-b88c-35970aeec8c2/skin/icon-light.png&quot;); cursor: auto;">
                </div>
        <div class="offset-lg-3 col-lg-5">
                            <div class="invalid-feedback">Cet utilisateur n'existe pas</div>
    </div>
        </div>
            <div class="form-group row">
        <div class="offset-lg-3 col-lg-5">
            <input class="btn btn-success" id="submit" name="submit" type="submit" value="R?cup?rer le mot de passe" data-_extension-text-contrast="">
    </div>
    </div>    
    </form>

<div class="invalid-feedback">Cet utilisateur n'existe pas</div>

But it does not shows on the page because .invalid-feedback is display: none;. Browsing loooong issues on bootstrap4 tracker the only thing I see is like adding d-block to this div to force it showing up.

Any ideas for this ?

Using Bootstrap switches for checkboxes

I would like to have a Bootstrap switch rendered for a checkbox. Ideally, I would like to enable this via a parameter when creating a BooleanField, but that is for later.

I have used the following lines to replace what is in form.html in order to get a switch rendered.

    {% if field.widget.input_type == 'checkbox' %}
        {% call _hz_form_wrap(horizontal_columns, form_type, True, required=required) %}
            <div class="custom-control custom-switch">
                <label class="custom-control-label">
                    {{ field(class_="custom-control-input")|safe }} {{ field.label.text|safe }}
                </label>
            </div>
        {% endcall %}

This renders a switch, see screenshot.

2019-12-07-140258_1920x1080_scrot

However, the switch is not responding to mouse clicks. How can this be fixed?

Second question is how to trigger this via a parameter in BooleanField?

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.