Bootstrap datepicker plugin

423 views
Skip to first unread message

Leonel Câmara

unread,
Jul 23, 2014, 2:40:47 PM7/23/14
to web...@googlegroups.com
So web2py's datepicker is horribly ugly this is yet another plugin to change it using http://www.eyecon.ro/bootstrap-datepicker. This one works nicely with bootstrap 3.

To use it simply import:

from plugin_bs_datepicker import bsdatepicker_widget

And then, in your field, set it as the widget for your field like in this example:

Field('birthdate', 'date', widget=bsdatepicker_widget)

Hopefully it's useful to anyone else.
web2py.plugin.bs_datepicker.w2p

Niphlod

unread,
Jul 23, 2014, 3:39:40 PM7/23/14
to web...@googlegroups.com
the only problem with various datepickers is internationalization. I'm a big fan of ISO format but finding a datepicker that adapts itself to strftime behaviour always seems to "escape" js developers ^_^

Leonel Câmara

unread,
Jul 23, 2014, 8:05:44 PM7/23/14
to web...@googlegroups.com
Niphlod if you look at my plugin's code you'll see that I took some precautions so that internationalization would work using the format defined in web2py_ajax.html on the variable w2p_ajax_date_format so if that's your concern you can probably use it.

Massimo Di Pierro

unread,
Jul 24, 2014, 3:24:28 AM7/24/14
to web...@googlegroups.com
html5 has <input type="date"...> and <input type="datetime"...>. web2py does not use them because very few browsers support them. I am wondering is there is js library that adds support for those input types in browsers that do not support them.

Leonel Câmara

unread,
Jul 24, 2014, 4:54:54 AM7/24/14
to web...@googlegroups.com
I'm open to extending this plugin so it accepts some settings, one of those settings could be - html5_if_available - and then, in the javascript, I could use something like Modernizr.inputtypes.date to check for browser support.

Otherwise I believe html5forms.js or webshim does what you want but they looked too complicated for me, I don't like complicated stuff.

Leonel Câmara

unread,
Jul 24, 2014, 11:48:49 AM7/24/14
to
New version supporting bootstrap picker options (weekStart, viewMode, minViewMode) except for format which is automatically determined by w2p_ajax_date.

This version is quite useful for stuff like birth dates where you want people to be able to choose the year easily.
web2py.plugin.bs_datepicker.w2p

villas

unread,
May 10, 2015, 9:46:22 PM5/10/15
to web...@googlegroups.com
Hi Leonel
I was trying out your widget but hit a problem...  maybe there is a bug? 
Best regards,  D

Traceback (most recent call last):
File "C:\Users\David\Documents\GitHub\web2py\gluon\restricted.py", line 227, in restricted
exec ccode in environment
File "C:/Users/David/Documents/GitHub/web2py/applications/prearrival/controllers/default.py", line 160, in <module>
File "C:\Users\David\Documents\GitHub\web2py\gluon\globals.py", line 393, in <lambda>
self._caller = lambda f: f()
File "C:\Users\David\Documents\GitHub\web2py\gluon\tools.py", line 3440, in f
return action(*a, **b)
File "C:/Users/David/Documents/GitHub/web2py/applications/prearrival/controllers/default.py", line 150, in passports
details = False,
File "C:\Users\David\Documents\GitHub\web2py\gluon\sqlhtml.py", line 2232, in grid
create_form = SQLFORM(table, **sqlformargs)
File "C:\Users\David\Documents\GitHub\web2py\gluon\sqlhtml.py", line 1229, in __init__
inp = field.widget(field, default)
TypeError: bsdatepicker_widget() takes at most 1 argument (2 given)

Leonel Câmara

unread,
May 11, 2015, 11:53:48 AM5/11/15
to web...@googlegroups.com
Here's the latest version with this fixed


web2py.plugin.bs_datepicker.w2p

villas

unread,
May 11, 2015, 5:01:36 PM5/11/15
to web...@googlegroups.com
Thanks Leonel.

BTW in your first post you said:   
    Field('birthdate', 'date', widget=bsdatepicker_widget) 

It should be with brackets at the end:
    Field('birthdate', 'date', widget=bsdatepicker_widget()) 

Manuele Pesenti

unread,
May 12, 2015, 3:46:51 AM5/12/15
to web...@googlegroups.com
Il 11/05/15 23:01, villas ha scritto:
No it shouldn't the widget parameter value sould be a callable.

M.

Leonel Câmara

unread,
May 12, 2015, 6:54:12 AM5/12/15
to web...@googlegroups.com
Villas is right, this function call returns the callable, it's this way so you can use bootstrap datepicker options.

diego...@gmail.com

unread,
Jul 4, 2016, 9:30:04 AM7/4/16
to web2py-users
Hi Leonel and all, (first post here)

Don't know if I'm reinveinting the wheel, but I was searching for a better datepicker and found your plugin. And liked so much that I modified it to make it work with a datepicker  fork -> https://github.com/eternicode/bootstrap-datepicker

To me works fine so I'm posting the code here for you to have a look at. Why aren't everybody using this?

Anyway thanks a lot!

P.S. How do we arrange for the beer? :)

# -*- coding: utf-8 -*-
"""
Integrates bootstrap-datepicker nicely into web2py.
Download the plugin at: https://github.com/eternicode/bootstrap-datepicker
"""



__author__
= 'Leonel Câmara'
__email__
= ''
__copyright__
= 'Copyright(c) 2014 Leonel Câmara'
__license__
= 'BEER-WARE'
__version__
= '0.12'
__status__
= 'Development'  # possible options: Prototype, Development, Production




from gluon import *
from gluon.sqlhtml import FormWidget


def bsdatepicker_widget(**settings):
   
"""
    Usage:
   
    from plugin_bs_datepicker import bsdatepicker_widget
    db.table.field.widget = bsdatepicker_widget()


    Examples:
    ## notice double quotes wrapping string parameters.
    db.table.field.widget = bsdatepicker_widget(
        startView=2, startDate="'-200y'", endDate="'0y'")
   
    ## pass a language code this way:
    langcode = 'it'
    db.table.field.widget = bsdatepicker_widget(
        language="'{0}'".format(langcode))


    look at:
    http://bootstrap-datepicker.readthedocs.org/en/stable/options.html
    for settings full list.
    """



   
def widget(field, value, **attributes):
       
default = {'value': value}
       
        attributes
= FormWidget._attributes(field, default, **attributes)
        attributes
['_class'] = 'form-control datepicker'
                   
        dateinput
= INPUT(**attributes)


       
## if language 'en' (default) remove setting, don't append locale script.
        locale
= ''
        lang
= settings.get('language', None)
       
if lang == "'en'":
           
del(settings['language'])
       
elif lang:
            url
= URL('static', 'plugin_bs_datepicker/locales/' \
               
'bootstrap-datepicker.{lang}.min.js'.format(lang=lang[1:-1]))
            locale
= "$('body').append($('<script src=\"{url}\"></script>'));".format(url=url)
       
        settings_str
= ',\n'.join(item[0] + ':' + str(item[1]) for item in
            settings
.iteritems()) if settings else ''
        javascript
= SCRIPT(
           
"""
            $('head').append($('<link href="
%(css_url)s" type="text/css" rel="stylesheet" />'));
            $.getScript('%(js_url)s').done(function(){
                %(locale_script)s
                $('#%(_id)s').datepicker({
                    format: w2p_ajax_date_format.replace('%%Y', 'yyyy').
                        replace('%%m', 'mm').replace('%%d', 'dd'),
                    %(settings)s
                })
            });
            """

           
% {
               
'css_url': URL('static', 'plugin_bs_datepicker/css/bootstrap-datepicker.css'),
               
'js_url': URL('static', 'plugin_bs_datepicker/js/bootstrap-datepicker.js'),
               
'locale_script': locale,
               
'_id': dateinput.attributes['_id'],
               
'settings': settings_str
           
})
       
return CAT(dateinput, javascript)


   
return widget



Ron Chatterjee

unread,
Jul 5, 2016, 12:10:44 PM7/5/16
to web2py-users
I had my fair share of evaluation. Which looks better?
datepicker.png

Donald McClymont

unread,
Jul 6, 2016, 8:17:59 AM7/6/16
to web2py-users
This is nice and a great improvement for dates.  I thought I could easily replicate for datetime by using this which seems to be a fork of the original to allow time input as well


however it seems to not be formatting the time selection correctly for some reason and may well need some adjustment to update with the script.  I will continue to look at getting working but if anyone else can provide some hints on how to do this then would be good to have both options available in some manner.

Donald

Donald McClymont

unread,
Jul 6, 2016, 6:59:02 PM7/6/16
to web2py-users
This now seems to be along the correct lines  - the issue I had was a styling conflict with calendar.css file in web2py for the hour class being set to 2em and my hack for now to fix was to append the following to the std datetimepicker.css that can  be downloaded however not sure if there is a better way.

/* To revernt font 2em in web2py calendar component */
.hour, .minute {font-size: 14px;}
plugin_bs_datepicker.py

Michael Beller

unread,
Jul 10, 2016, 10:31:24 PM7/10/16
to web2py-users
I'm using bootstrap-datepicker.js also with these changes, not sure it's as robust but works and I use it for multiple date formats such as this:

    Field('origination_date', 'date',
          widget
=datepicker_widget(format='mm/yyyy', min_view_mode='months'), requires=IS_DATE('%m/%Y')),  # example using just mm/yyyy

added widget
def datepicker_widget(**settings):


   
def widget(field, value, **attributes):
       
default = {'value': value}
        attributes
= FormWidget._attributes(field, default, **attributes)

        attributes
['_class'] = 'form-control date'

       
# default format “mm/dd/yyyy”
        data_attributes
= {}
        data_attributes
['date-format'] = 'yyyy-mm-dd'
       
for item in settings.iteritems():
            data_attributes
['date-'+item[0].replace('_', '-')] = item[1]

       
return INPUT(
            data
=data_attributes,
           
**attributes
       
)

   
return widget


added this to my layout (I actually place this in a .js file I then add to layout.html:
$('input.date').datepicker({
     todayBtn
: "linked",
     autoclose
: true,
     todayHighlight
: true
});

I removed for web2py_ajax.html:
# response.files.insert(1,URL('static','css/calendar.css'))
# response.files.insert(2,URL('static','js/calendar.js'))
Reply all
Reply to author
Forward
0 new messages