[Django]-Add Calendar Widget to Django Form

3👍

I use bootstrap-daterangepicker: https://github.com/dangrossman/bootstrap-daterangepicker. It would bind the widget’s change to your django form field, so you don’t need to manipulate the data once it comes to the views.py.

To get more details you should download and play with it, but here’s a rough idea:

Your form.py:

class DateRangeForm(forms.Form):
    start_date = forms.DateField()
    end_date = forms.DateField()

    def __init__(self, *args, **kwargs):
        # initialize the start and end with some dates

Your template:

<div class="daterangepicker-container mcast-search-filter">                                                                             
    <div class="daterangepicker-label">Date range:</div>                                                                                
    <div id="daterange" class="daterangepicker-content">                                                                                
        <i class="icon-calendar icon-large"></i>                                                                                        
        <span></span> <b class="caret"></b>                                                                                             
    </div>                                                                                                                              
</div>                                                                                                                                  

<!-- This is a hidden div that holds your form fields -->                                                                                                                                           
<div class="hide">From {{ daterange_form.start_date }} to {{ daterange_form.end_date }}</div>

To trigger the widget you need a javascript binding:

// the id_start_date and id_end_date are the ids that django form fields created
$("#daterange").initDateRangePicker("#id_start_date", "#id_end_date");

I created a datepicker wrapper, and defined the initDateRangePicker function. You should put following code in a file called daterangepicker.js and import that in your template as well(or simply copy it into your template):

(function($) {                                                                                                                                      
    $.fn.initDateRangePicker = function(start_date_el, end_date_el, future) {                                                                       
        return this.each(function() {                                                                                                               
            var start = moment($(start_date_el).val());                                                                                             
            var end = moment($(end_date_el).val());                                                                                                 

            var display_date = function(start, end) {                                                                                               
                var str = ""                                                                                                                        
                str += start.format('MMMM Do, YYYY');                                                                                               
                str += " - ";                                                                                                                       
                str += end.format('MMMM Do, YYYY');                                                                                                 

                return str;                                                                                                                         
            };                                                                                                                                      

            $(this).find("span").html(display_date(start, end));                                                                                    
            var self = this;                                                                                                                        

            if(!future) {                                                                                                                           
                $(this).daterangepicker({                                                                                                           
                    format: 'YYYY-MM-DD',                                                                                                           
                    timePicker: false,                                                                                                              
                    ranges: {                                                                                                                       
                        'Last 7 days': [moment().subtract('days', 6), moment()],                                                                    
                        'Month to date': [                                                                                                          
                            moment().startOf('month'),                                                                                              
                            moment(),                                                                                                               
                        ],                                                                                                                          
                        'Last Month': [                                                                                                             
                            moment().subtract('month', 1).startOf('month'),                                                                         
                            moment().subtract('month', 1).endOf('month'),                                                                           
                        ]                                                                                                                           
                    },                                                                                                                              
                }, function(start, end) {                                                                                                           
                    $(start_date_el).val(start.format('YYYY-MM-DD'));                                                                               
                    $(end_date_el).val(end.format('YYYY-MM-DD'));                                                                                   

                    $(self).find("span").html(display_date(start, end));                                                                            
                });                                                                                                                                 
            }                                                                                                                                       
            else {                                                                                                                                  
                 $(this).daterangepicker({                                                                                                          
                    format: 'YYYY-MM-DD',                                                                                                           
                    timePicker: false,                                                                                                              
                    ranges: {                                                                                                                       
                        'Next 7 days': [moment().add('days', 1), moment().add('days', 7)],                                                          
                        'Next month': [                                                                                                             
                            moment().add('month', 1).startOf('month'),                                                                              
                            moment().add('month', 1).endOf('month'),                                                                                
                        ],                                                                                                                          
                    },                                                                                                                              
                }, function(start, end) {                                                                                                           
                    $(start_date_el).val(start.format('YYYY-MM-DD'));                                                                               
                    $(end_date_el).val(end.format('YYYY-MM-DD'));                                                                                   

                    $(self).find("span").html(display_date(start, end));                                                                            
                });                                                                                                                                 

            }                                                                                                                                       
        });                                                                                                                                         
    };                                                                                                                                              
}).call(this, jQuery);

Leave a comment